js中几种继承方法

1.原型继承

  function Foo(name){
        this.name = name;
    }
    Foo.prototype.myName = function(){  
        return this.name;
    }

    function Bar(name,label){
        Foo.call(this,name);    //此处实际上也应用了构造函数继承
        this.label = label;
    }

    Bar.prototype = Object.create(Foo.prototype);
    Bar.prototype.myLabel = function(){
        return this.label;
    }

    var a = new Bar("a","obj a");
    a.myName();
    a.myLabel();

这段代码的核心部分就是

Bar.prototype = Object.create(Foo.prototype);

调用 Object.create(Foo.prototype); 会凭空创建一个"新"对象并把对象内部的[[Prototype]]关联到你的指定对象。

换句话说,这条语句的意思是:创建一个新的Bar.prototype对象并把它关联到Foo.prototype. 

2.组合继承
    function Foo(name){
        this.name = name;
        this.color = ["red","blue"];
    }

    Foo.prototype.sayName = function(){
        alert(this.name)
    }

    function Bar(name,age){
        Foo.call(this,name);
        this.age = age;
    }

    Bar.prototype = new Foo();
    Bar.prototype.constructor = Bar;
    Bar.prototype.sayAge = function(){
        alert(this.age);
    }
    var a = new Bar("nicholas",29);
3.寄生继承
 function Foo(original){
        var clone = object(original);   //通过调用函数创建一个新对象
        clone.sayHi = function(){       //以某种方式来增强这个对象
            alert("hi")                 
        }
        return clone;                   //返回这个对象
    }

function object(o) {
    function F(){}
    F.prototype = o;
    return new F();
}
//object内部,先创建一个临时性的构造函数,然后将传入的对象作为这个构造函数的原型,最后返回这个临时类型的一个新实例。从本质上讲,object()对传入其中的对象进行了浅复制。
    var person = {
        name : "nicholas",
        friend: ["shelby","court","van"]
    }

    var  anotherPerson = Foo(person);
    anotherPerson.sayHi()
   

猜你喜欢

转载自blog.csdn.net/weixin_41658426/article/details/80761198