function Super () { this.name = 'zhanhui'; this.say = function () { console.log(this.name); } } Super.prototype.getSuper = function () { console.log(this); } function Sub () { this.age = 26 this.howOld = function () { console.log(this.age); } } Sub.prototype = new Super(); // 知道new的過程,就知道這裏是新建立了一個新的對象 var obj = new Sub(); console.log(obj instanceof Object); // true console.log(obj instanceof Sub); // true console.log(obj instanceof Super); // true
Object.prototype.isPrototypeOf(obj); // true Sub.prototype.isPrototypeOf(obj); // true Super.prototype.isPrototypeOf(obj); // true
// 添加新的方法 Sub.prototype.getSub = function () { console.log(true); } // 覆蓋超類中的方法 Sub.prototype.getSuper = function () { console.log(false); } var obj1 = new Sub(); Sub.getSuper() // false var superObj = new Super(); superObj.getSuper(); // superObj
function Super (name) { this.name = name; this.friends = ['mike', 'boo'] } Super.prototype.sayName = function () { console.log(this.name); } function Sub () { Super.call(this); // 第二次調用超類對象 this.age = 26; } Sub.prototype = new Super(); //第一次調用超類對象 Sub.prototype.constructor = Sub; Sub.prototype.sayAge = function () { console.log(this.age); }
function (original) { var clone = Object.create(original); // 建立的新對象的__proto__指向original clone.say = function () { console.log(true); } return clone; }
function superObj (name){ this.name = name; this.firends = [1,2,3]; } superObj.prototype.say = function(w) { console.log(w); }; function subObj (name) { superObj.call(this,name); } subObj.prototype = Object.assign(Object.create(superObj.prototype),{ constructor: subObj })