JS继承法汇总

对象冒充法

 

//js继承汇总 //1、对象冒充法继承法 function A(name) { this.name = name; this.say = function() { alert(name); }; } function B(id,name) { this.methodA = A; this.methodA(name); delete this.methodA; this.id = id; this.sayId = function() { alert(id); }; } var a = new A("a"); a.say(); var b = new B(1,"b"); b.say();

 

原型链继承法

 

 

//2、原型链继承法 prototype function A(name) { this.name = name; } A.prototype.say=function() { alert(this.name); }; function B(id,name) { this.id = id; this.name = name; } B.prototype.sayId = function() { alert(this.id); }; B.prototype = new A; var a = new A('a'); var b = new B(1,'b'); a.say(); b.say(); var a1 = new A('c'); a1.say();

 

call 继承法

 

//3、call apply法 function A(name) { this.name = name; this.say = function() { alert(name); }; } function B(id,name) { A.call(this,name); this.id = id; this.name = name; this.sayId = function() { alert(id); }; } var a = new A('a'); a.say(); var b = new B(1,'b'); b.say();

 

 

apply继承法

 

//3、call apply法 function A(name) { this.name = name; this.say = function() { alert(name); }; } function B(id,name) { A.apply(this,[name]); this.id = id; this.name = name; this.sayId = function() { alert(id); }; } var a = new A('a'); a.say(); var b = new B(1,'b'); b.say();

你可能感兴趣的:(JS继承法汇总)