js種new的過程和js繼承的記錄

new操作符的工作原理是什么?它是怎么樣改變構造函數(shù)的返回值和this指向的?

我們都知道new運算符是用來實例化一個類,從而在內(nèi)存中分配一個實例對象。
如下: var person = new Person();
實際上經(jīng)歷了四個階段:
1.創(chuàng)建一個新的對象;
2.將構造函數(shù)的作用域賦給新對象,(因此this就指向了這個新對象)
3.執(zhí)行構造函數(shù)中的代碼(為這個新對象添加屬性)
4.返回新對象
具體來看代碼如下過程:

 let person = {};
 person._proto_ = Person.prototype;
 Person.call(person)

這就是new操作符的操作全過程了。

js中常見的繼承方式

1:原型繼承

function Father(){
this.property = true;
}
Father.prototype.getValue = function(){
  return this.property;
}

function Son(){
this.Sonproperty = false;
}
//繼承Father
Son.prototype = new Father();//原型重寫,constructor被改寫
Son.prototype.constructor = Son;//重寫指向Son
Son.prototype.getSonValue = function(){
return this.property;
}
var instance = new Son();
console.log(instance.getValue());//true

原型繼承的缺點有:
1:引用原型值會被所有實例共享
2:子類無法向父類傳參

2:借用函數(shù)繼承(經(jīng)典繼承)

//基本思想:在子類型構造函數(shù)中調(diào)用超類型的構造函數(shù)

function Father(){
this.colors = ['red','blue','green'];
name = 'haha';
}
function Son(){
Father.call(this);//繼承Father,并向父類型傳參
}
Son.prototype = new Father();
var instance1 = new Son();
instance1.colors.push('black');
console.log(instance1.colors);
var instance2 = new Son();
instance2.colors.push('pink');
console.log(instance2.colors);
//此種繼承方法解決了原型鏈繼承所存在的兩個問題,但是依然存在構造函數(shù)無法復用的問題

3:組合繼承(偽經(jīng)典繼承)--經(jīng)常使用

此種組合繼承的方法就是集合了上面兩種方法的各自優(yōu)點,
基本思路:使用原型鏈實現(xiàn)對原型屬性和方法的繼承,通過借用構造函數(shù)來實現(xiàn)對實例屬性的繼承

function Father(name){
this.name = name;
this.colors = ["red","pink","green"];
}

Father.prototype.sayname = function(){
console.log(this.name);
}

function Son(name,age){
Father.call(this,name);//使用構造函數(shù)進行實例屬性的繼承
this.age = age;
}

Son.prototype = new Father();//使用原型鏈繼承超類型方法
Son.prototype.constructor = Son;//重新指向Son
Son.prototype.sayage = function(){
console.log(this.age);
}

var instance1 = new Son("lisi",12);
instance1.colors.push("brown");
console.log(instance1.colors);
instance1.sayname();
instance1.sayage();

var instance2 = new Son("hah",22);
instance2.colors.push("black");
console.log(instance2.colors);
instance2.sayname();
instance2.sayage();
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容