JS構(gòu)造函數(shù)和實例化的關系及原型引入
1、 構(gòu)造函數(shù)與實例化
當我們的編程是面向?qū)ο蟮臅r候,先是抽象的過程=>然后實例化的過程,比如我們抽象一個人,我知道一個人的基本信息。名稱,年齡,性別,....等等
我們把先是抽象的,在抽象完成后,我們在實例化。
2、構(gòu)造函數(shù)與實例化之間的關系?
//這個自定義的構(gòu)造函數(shù)在抽象
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
this.say=function(){
console.log("我叫",name)
}
}
// 這個過程是實例化
let per1=new Person('司藤',300,'女');
per1.say();//調(diào)用
//let per1=new Person('司藤',300,'女');
通過上面這一行代碼。
我們可以得出一個結(jié)論:
構(gòu)造函數(shù)與實例對象之間的關系是:
實例對象需要通過構(gòu)造函數(shù)來創(chuàng)建的。
同時:我們可以知道實例對象的構(gòu)造器就是構(gòu)造函數(shù)
我們來證明這一句話是否正確;上面的代碼不改變。
console.log( per1.constructor===Person ) //返回的是true
充分說明:實例對象的構(gòu)造器就是構(gòu)造函數(shù)這一句話是正確的。
3、per1.say是否等于per2.say
function Person(name,age,like) {
this.name=name;
this.age=age;
this.like=like;
this.say=function(){
console.log('我可以不吃飯');
}
}
var per1=new Person("司藤",300,'耍');
var per2=new Person('白淺','10000','耍');
per1.say();
per2.say();
console.log( per1.say==per2.say ) //false
4、per1.say不等于per2.say得出的結(jié)論
因為console.log( per1.say==per2.say ) //false
我們可以得出一個結(jié)論。
那就是per1.say()和per2.say()調(diào)用的不是同一個方法
那么他們的內(nèi)容是否是相等的的呢?
console.log( per1.say()==per2.say() ) //true
說明內(nèi)容是相等的
5、舉例代碼問題
5.1代碼出現(xiàn)的問題
function Person(name,age,like) {
this.name=name;
this.age=age;
this.like=like;
this.say=function(){
console.log('我可以不吃飯');
}
};
for (var index = 0; index < 100; index++) {
var per=new Person("司藤",300,'耍');
per.say();
}
這一段代碼:是它在內(nèi)存中開辟了100個空間。每個空間都有一個say方法。但是每一個say方法都是不同的??墒撬麄冚敵龅膬?nèi)容是相同?;蛘哒f執(zhí)行的邏輯是相同的。這樣就造成了空間浪費。所以在項目中,這樣就造成了浪費空間。
我們可不可以來優(yōu)化呢 ?
5.2優(yōu)化代碼解決造成空間浪費
function comSay(){
// 執(zhí)行相同的邏輯
console.log('我可以不吃飯')
};
function Person(name,age,like) {
this.name=name;
this.age=age;
this.like=like;
this.say=comSay;//不要加括號
};
var per1=new Person("司藤",300,'耍');
var per2=new Person('白淺','10000','耍');
console.log( per1.say==per2.say ) //true
這樣我們就節(jié)約了空間。每次調(diào)用的時候,都是同一個方法。
5.3處理使用這種方法,我們還可以使用原型的方式
function Person(name,age,like) {
this.name=name;
this.age=age;
this.like=like;
};
Person.prototype.comSay=function(){
console.log('我可以不吃飯')
}
var per1=new Person("司藤",300,'耍');
var per2=new Person('白淺','10000','耍');
console.log( per1.comSay==per2.comSay ) //true
// 我們還可以通過原型來解決數(shù)據(jù)共享
原型的作用:數(shù)據(jù)共享,節(jié)約空間。
到此這篇關于JS構(gòu)造函數(shù)和實例化的關系及原型引入的文章就介紹到這了,更多相關JS構(gòu)造函數(shù)和實例化的關系及原型引入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Uncaught EvalError:Refused to evaluate a
這篇文章主要為大家介紹了Uncaught EvalError:Refused to evaluate a string as JavaScript解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09

