先上代碼
function Person(name) {
this.weight = 7;
this.height = 14;
this.skin = "yellow";
this.gender = "";
this.name = name;
this.age = 0;
}
Person.prototype.eat = function () {
console.log("喫喫");
};
Person.prototype.cry = function () {
console.log("哭哭");
};
var person1 = new Person;
function pe() {
}
pe.prototype.txt=function(){
console.log("a");
}
pe.prototype = new Person;
var tom = new pe;
pe.prototype.writeCss = function () {
console.log("我會")
};
pe.prototype.writeJs = function () {
console.log("JS");
};
咱們先分析下代碼
首先我們構造了一個Person的構造函數,並在Person的共享中,即Person.prototype中加入了兩個屬性即 eat和cry
此時圖形是這樣的
並且 我們創建了一個person1的實例 圖就變爲
然後 我們又創建了一個構造函數pe,並讓其pe.prototype=new Person
圖形則變爲
然後再Pe下創建了一個tom的實例,再到 pe.prototype這個共享內再創建兩個方法即 writeCss跟writeJs
圖形則變爲
這樣我們就完成了 原型的繼承
如果我們將代碼改爲這樣
// pe.prototype = new Person;
pe.prototype.__proto__=Person.prototype;
圖就要改爲這樣
原來pe.prototype中繼承的Person私有的一些方法就沒有了
若將代碼改成這樣
// pe.prototype = new Person;
pe.prototype=Person.prototype;
// pe.prototype.__proto__=Person.prototyp
圖形這要變成這樣
此時pe跟person就共享了同一個prototype
以上是個人學習的一點心得,歡迎指正