1. 程式人生 > >原型式繼承

原型式繼承

創建 false zha pan ngs class 繼承 say console

實例1:

function Obj(o){
        function f(){};
        f.prototype = o;
        return new f();
    }
    
    function person(name,age){
        this.name = name;
        this.age = age;
    }

    person.prototype.say = function(){
        console.log(this.name+‘ : ‘+this.age);
    }
    var p1 = Obj(new
person(‘zhangsan‘,23)); var p2 = Obj(new person(‘zhangsan‘,23)); console.log(p1); console.log(p2); console.log(p1.__proto__ === p2.__proto__);//false console.log(p1.__proto__.__proto__ === p2.__proto__.__proto__);//true p1.name1 = ‘zhangsan‘; p2.name1 = ‘lisi‘; p1.__proto__.name
= ‘liuliu‘; console.log(p1); console.log(p2);

借助原型可以基於已有的對象創建新的對象;

但是P1和P2是兩個獨立的對象,原型是一樣的;

原型式繼承