淺談javascript中的constructor
constructor,構(gòu)造函數(shù),對(duì)這個(gè)名字,我們都不陌生,constructor始終指向創(chuàng)建當(dāng)前對(duì)象的構(gòu)造函數(shù)。
這里有一點(diǎn)需要注意的是,每個(gè)函數(shù)都有一個(gè)prototype屬性,這個(gè)prototype的constructor指向這個(gè)函數(shù),這個(gè)時(shí)候我們修改這個(gè)函數(shù)的prototype時(shí),就發(fā)生了意外。如
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.getAge = function(){
return this.age;
}
Person.prototype.getName = function(){
return this.name;
}
var p = new Person("Nicholas",18);
console.log(p.constructor); //Person(name, age)
console.log(p.getAge()); //18
console.log(p.getName()); //Nicholas
但是如果是這樣:
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
}
var p = new Person("Nicholas",18);
console.log(p.constructor); //Object()
console.log(p.getAge()); //18
console.log(p.getName()); //Nicholas
結(jié)果constructor變了。
原因就是prototype本身也是對(duì)象,上面的代碼等價(jià)于
Person.prototype = new Object({
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
});
因?yàn)閏onstructor始終指向創(chuàng)建當(dāng)前對(duì)象的構(gòu)造函數(shù),那么就不難理解上面代碼p.constructor輸出的是Object了。
對(duì)于修改了prototype之后的constructor還想讓它指向Person怎么辦呢?簡(jiǎn)單,直接給Person.prototype.constructor賦值就可以了:
Person.prototype = {
constructor:Person,
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
}
以上這篇淺談javascript中的constructor就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- 一文徹底理解js原生語法prototype,__proto__和constructor
- js構(gòu)造函數(shù)constructor和原型prototype原理與用法實(shí)例分析
- 幫你徹底搞懂JS中的prototype、__proto__與constructor(圖解)
- js核心基礎(chǔ)之構(gòu)造函數(shù)constructor用法實(shí)例分析
- javascript設(shè)計(jì)模式Constructor(構(gòu)造器)模式
- npm出現(xiàn)Cannot?find?module?'XXX\node_modules\npm\bin\npm-cli.js'錯(cuò)誤的解決方法
- CommonJS與ES6?Module的使用區(qū)別分析
- JavaScript ES6 Module模塊詳解
- 全面解析JavaScript Module模式
- 利用webpack理解CommonJS和ES Modules的差異區(qū)別
- Javascript? Constructor構(gòu)造器模式與Module模塊模式
相關(guān)文章
Js刪除數(shù)組中某一項(xiàng)或幾項(xiàng)的幾種方法(推薦)
下面小編就為大家?guī)硪黄狫s刪除數(shù)組中某一項(xiàng)或幾項(xiàng)的幾種方法(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-07-07
實(shí)例講解JavaScript中的this指向錯(cuò)誤解決方法
JavaScript中this指向的處理是令大家普遍頭疼的問題,這里我們舉一個(gè)實(shí)例講解JavaScript中的this指向錯(cuò)誤解決方法,需要的朋友可以參考下2016-06-06
javaScript知識(shí)點(diǎn)總結(jié)(必看篇)
下面小編就為大家?guī)硪黄猨avaScript知識(shí)點(diǎn)總結(jié)(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享 給大家,也給的大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
關(guān)于JavaScript的變量的數(shù)據(jù)類型的判斷方法
這篇文章主要介紹了關(guān)于JavaScript的變量的數(shù)據(jù)類型的判斷方法,JS是一種弱類型語言,其數(shù)據(jù)類型的相關(guān)特性有時(shí)也受到不少開發(fā)者的詬病,需要的朋友可以參考下2015-08-08

