美文网首页
Javascript 继承

Javascript 继承

作者: 已注销null | 来源:发表于2016-11-09 20:11 被阅读0次

    参考:
    JavaScript高级程序设计(第3版)

    • 原型链
    function SuperType() {
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function () {
      return this.property;
    }
    
    function Subtype() {
      this.subproperty = false;
    }
    
    // 继承了SuperType
    SubType.prototype = new SuperType();
    
    SubType.prototype.getSubValue = function() {
      return this.subproperty;
    }
    
    var instance = new SubType();
    console.log(instance.getSuperValue) // true;
    
    • 原型式继承
    function object(o) {
      function F() {}
      F.prototype = o;
      return new F();
    }
    
    var person = {
      name: "Nicolars",
      friends: ["s", "c", "v"]
    };
    
    var A = object(person);
    A.name = "G";
    A.friends.push("r");
    
    var B = object(person);
    B.name = "L";
    B.friends.push("f");
    
    console.log(person.friends) // "s, c, v, r, f"
    
    • 寄生式继承
    function createAnother(origin) {
      var clone = object(origin);
      clone.sayHi = function() {
        console.log("HI");
    }
      return clone;
    }
    
    var person = {
      name: "N",
      friends: ["s", "c", "v"]
    };
    
    var anotherPerson = createAnother(person);
    anotherPerson.sayHi(); // HI
    
    • 寄生组合式继承
    function SuperType(name) {
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function () {
      console.log(this.name);
    }
    
    function SubType(name, age) {
      SuperType.call(this. name); 
      this.age = age;
    }
    
    SubType.prototype = new SuperType();
    SubType.prototype.constructor = SubType;
    SubType.prototype.sayAge = function() {
      console.log(this.age);
    }
    

    相关文章

      网友评论

          本文标题:Javascript 继承

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