美文网首页
js一些技巧.md

js一些技巧.md

作者: _无为_ | 来源:发表于2018-11-27 11:33 被阅读0次

js中的constructor和prototype

组合继承与寄生继承

  function Parent(name){
        this.name = name;
        this.methods = function(){
              console.log("do someThing")
        }
  }

组合继承

function Children(name){
      Parent.call(this);  // 1. 拷贝属性
      this.name = name || 'zhangsan';
}
Children.prototype = new Parent();  //2. 原型指向父类实例
Children.prototype.constructer = Children; 3. 修正constructor 指向
  1. 可以继承实例属性和方法,也可以继承原型属性和方法
  2. 是子类实例,也相当于父类实例
  3. 子类原型指向父类实例,该父类实例又可以向上原型查找访问,修正constructor指向子类自身
  4. 可传参,call 方法可传参
  5. 调用两次父类构造函数, 占内存, 第一步拷贝过一次, 第二步导致以后的Jianren的实例里和Jianren原型上重复的属性

寄生组合类型

function Children(name){
      Parent.call(this);  // 1. 拷贝属性
      this.name = name || 'zhangsan';
}
(function(){
    function Storage(){}  // 创建一个中间类,空
    Storage.prototype  = Paren.prototype; //将中间类指向父类原型
    Children.prototype = new Storage(); //子类原型赋值中间类实例,往上查找,指向父类的原型
})()
Children.prototype.constructor = Children; // 修正子类constructor指向

与上面的组合继承相比, 第一步拷贝 和 第二步中间类(空类)不会重复有Human的属性, 略微复杂, 可以忽略不计, 完美方式

相关文章

网友评论

      本文标题:js一些技巧.md

      本文链接:https://www.haomeiwen.com/subject/wkqiqqtx.html