淺談javascript中的constructor
constructor,構(gòu)造函數(shù),對這個(gè)名字,我們都不陌生,constructor始終指向創(chuàng)建當(dāng)前對象的構(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本身也是對象,上面的代碼等價(jià)于
Person.prototype = new Object({ getName:function(){ return this.name; }, getAge:function(){ return this.age; } });
因?yàn)閏onstructor始終指向創(chuàng)建當(dāng)前對象的構(gòu)造函數(shù),那么就不難理解上面代碼p.constructor輸出的是Object了。
對于修改了prototype之后的constructor還想讓它指向Person怎么辦呢?簡單,直接給Person.prototype.constructor賦值就可以了:
Person.prototype = { constructor:Person, getName:function(){ return this.name; }, getAge:function(){ return this.age; } }
以上這篇淺談javascript中的constructor就是小編分享給大家的全部內(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)文章
JavaScript的函數(shù)式編程基礎(chǔ)指南
這篇文章主要介紹了JavaScript的函數(shù)式編程基礎(chǔ)指南,雖然JavaScript被許多人一再強(qiáng)調(diào)面向?qū)ο?但js中卻沒有類,而本文所展現(xiàn)的函數(shù)主導(dǎo)的js編程則同樣可以很爽,需要的朋友可以參考下2016-03-03JavaScript起點(diǎn)(嚴(yán)格模式深度了解)
嚴(yán)格模式(Strict Mode)是ECMAScript5新增的功能,目前所有的主流瀏覽器的最新版本——包括IE10與Opera12——都支持嚴(yán)格模式,感興趣的朋友可以了解下啊,希望本文對你有所幫助2013-01-01如何獲取JQUERY AJAX返回的JSON結(jié)果集實(shí)現(xiàn)代碼
我寫了個(gè)方法,用于查詢結(jié)果,但debug過程中發(fā)現(xiàn)結(jié)果集有數(shù)據(jù),我如何通過變量獲取呢2012-12-12表單元素的submit()方法和onsubmit事件應(yīng)用概述
表單元素?fù)碛衧ubmit方法,同時(shí)也具有onsubmit事件句柄,用于監(jiān)聽表單提交??梢允褂胑lemForm.submit();方法觸發(fā)表單提交,感興趣的朋友可以了解下,或許對你有所幫助2013-02-02javascript設(shè)計(jì)模式之鴨子類型和多態(tài)
這篇文章主要為大家介紹了javascript鴨子類型和多態(tài),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助<BR>2022-01-01