本篇內(nèi)容介紹了“JavaScript的constructor怎么定義使用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿(mǎn)足客戶(hù)于互聯(lián)網(wǎng)時(shí)代的漣源網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
定義和用法
constructor 屬性返回對(duì)創(chuàng)建此對(duì)象的數(shù)組函數(shù)的引用。
語(yǔ)法
object.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怎么定義使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
網(wǎng)站標(biāo)題:JavaScript的constructor怎么定義使用
網(wǎng)頁(yè)地址:http://chinadenli.net/article2/joejoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、微信公眾號(hào)、軟件開(kāi)發(fā)、電子商務(wù)、網(wǎng)站設(shè)計(jì)、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)