淺談javascript中的constructor
constructor,構造函數(shù),對這個名字,我們都不陌生,constructor始終指向創(chuàng)建當前對象的構造函數(shù)。
這里有一點需要注意的是,每個函數(shù)都有一個prototype屬性,這個prototype的constructor指向這個函數(shù),這個時候我們修改這個函數(shù)的prototype時,就發(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
結果constructor變了。
原因就是prototype本身也是對象,上面的代碼等價于
Person.prototype = new Object({ getName:function(){ return this.name; }, getAge:function(){ return this.age; } });
因為constructor始終指向創(chuàng)建當前對象的構造函數(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 一文徹底理解js原生語法prototype,__proto__和constructor
- js構造函數(shù)constructor和原型prototype原理與用法實例分析
- 幫你徹底搞懂JS中的prototype、__proto__與constructor(圖解)
- js核心基礎之構造函數(shù)constructor用法實例分析
- javascript設計模式Constructor(構造器)模式
- npm出現(xiàn)Cannot?find?module?'XXX\node_modules\npm\bin\npm-cli.js'錯誤的解決方法
- CommonJS與ES6?Module的使用區(qū)別分析
- JavaScript ES6 Module模塊詳解
- 全面解析JavaScript Module模式
- 利用webpack理解CommonJS和ES Modules的差異區(qū)別
- Javascript? Constructor構造器模式與Module模塊模式
相關文章
如何獲取JQUERY AJAX返回的JSON結果集實現(xiàn)代碼
我寫了個方法,用于查詢結果,但debug過程中發(fā)現(xiàn)結果集有數(shù)據(jù),我如何通過變量獲取呢2012-12-12表單元素的submit()方法和onsubmit事件應用概述
表單元素擁有submit方法,同時也具有onsubmit事件句柄,用于監(jiān)聽表單提交??梢允褂胑lemForm.submit();方法觸發(fā)表單提交,感興趣的朋友可以了解下,或許對你有所幫助2013-02-02