继承(原型)

1.过多继承没用属性

//继承
// function Test(name,age) {
// this.name = name;
// this.age = age;
// }
// function Test1(name,age,hobby){
// Test.call(this,name,age);
// this.hobby = hobby;
// }
// var test1 = new Test1('w',15,'喝酒');

// function inherit (Target,Origin) {
// function F() {};
// F.prototype = Origin.prototype;
// Target.prototype = new F();
// }
// Father.prototype.lastName = 'Deng';
// function Father() {

// }
// function Son() {

// }
// inherit(Son,Father);
// var son = new Son();
// var father = new Father();

 

2.借用构造函数:每次调用都要走两次函数(执行效率增加)

// function P(name,age) {
// this.name = name;
// this.age = age;
// }
// function T(name,age,sex) {
// P.call(this,name,age);
// this.sex = sex;
// }
// var t = new T();

 

3//.继承共有对象
// P.prototype.name = 'wsx';
// function P() {

// }
// function W() {

// }
// function inherit(Target,Orgin) {
// Target.prototype = Orgin.prototype;
// }
// inherit(W,P);
// var w = new W();
// var p = new P();

 

4.圣杯,两种写法:

一.

// function inherit(Target,Origin) {
// function T() {}
// T.prototype = Origin.prototype;
// Target.Prototype = new T();
// Target.prototype.constuctor = Target;//调用P
// Target.prototype.uber = Origin.prototype;
// }
// //H.prototype.name = 'wkn';
// P.prototype.name = 'wsx';
// function P() {

// }
// function H() {

// }
// inherit(H,P);
// var h = new H();//undefined
// var p = new P();//wkn,wsx

二。

//立即执行函数
var inherit = (function() {
function F() {};
return function (Target,Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
}

});
A.prototype.name = 'wsx';
function A() {

}
function B() {

}
inherit(A,B);
var a = new A();//wsx
var b = new B();//undefined

posted on 2022-07-13 23:05  爱前端的小魏  阅读(23)  评论(0编辑  收藏  举报

导航