我的CSDN博客地址: http://blog.csdn.net/caicongyang
//对象冒充 function Parent(username) { this.username = username; this.sayName = function() { alert(this.username); }; } function Chlid(username,age){ this.method = Parent; this.method(username); delete this.method; this.age = age; this.sayAge = function (){ alert(this.age); }; } var parent = new Parent("Tom1"); parent.sayName(); var chlid = new Chlid("Tom2","23"); chlid.sayName(); chlid.sayAge();
//call方式 function Parent(username) { this.username = username; this.sayName = function() { alert(this.username); }; } function Chlid(username,age){ Parent.call(this, username); this.age = age; this.sayAge = function(){ alert(this.age); }; } var parent = new Parent("C"); parent.sayName(); var chlid = new Chlid("C++","25"); chlid.sayName(); chlid.sayAge();
//apply方式 function Parent(username) { this.username = username; this.sayName = function() { alert(this.username); }; } function Chlid(username,age){ Parent.apply(this, new Array(username)); this.age = age; this.sayAge = function(){ alert(this.age); }; } var parent = new Parent("C"); parent.sayName(); var chlid = new Chlid("JAVA","25"); chlid.sayName(); chlid.sayAge();
//propotyes chain 方式实现继承 function Parent(){ } Parent.prototype.name = "lisi"; Parent.prototype.sayName = function(){ alert(this.name); }; function Child(){ } Child.prototype = new Parent(); Child.prototype.age = "18"; Child.prototype.sayAge = function(){ alert(this.age); }; var parent = new Parent(); parent.sayName(); var Child = new Child(); Child.sayName(); Child.sayAge();
//混合方式(推荐) function Parent(name){ this.name = name; } Parent.prototype.sayName = function(){ alert(this.name); }; function Child(name,age){ Parent.call(this, name); this.age = age; }; Child.prototype = new Parent(); Child.prototype.sayAge = function(){ alert(this.age); }; var parent = new Parent("c"); parent.sayName(); var Child = new Child("java","13"); Child.sayName(); Child.sayAge();
我的CSDN博客地址: http://blog.csdn.net/caicongyang