js中的constructor
定義和用法
constructor 屬性返回對創(chuàng)建此對象的 Date 函數(shù)的引用。
語法
object.constructor
constructor屬性不影響任何JavaScript的內(nèi)部屬性。instanceof檢測對象的原型鏈,通常你是無法修改的(不過某些引擎通過私有的__proto__屬性暴露出來)。
constructor其實沒有什么用處,只是JavaScript語言設(shè)計的歷史遺留物。由于constructor屬性是可以變更的,所以未必真的指向?qū)ο蟮臉?gòu)造函數(shù),只是一個提示。不過,從編程習(xí)慣上,我們應(yīng)該盡量讓對象的constructor指向其構(gòu)造函數(shù),以維持這個慣例。
舉個例子
var a,b;
(function(){
function A (arg1,arg2) {
this.a = 1;
this.b=2;
}
A.prototype.log = function () {
console.log(this.a);
}
a = new A();
b = new A();
})()
a.log();
// 1
b.log();
// 1
通過以上代碼我們可以得到兩個對象,a,b,他們同為類A的實例。因為A在閉包里,所以現(xiàn)在我們是不能直接訪問A的,那如果我想給類A增加新方法怎么辦?
// a.constructor.prototype 在chrome,firefox中可以通過 a.__proto__ 直接訪問
a.constructor.prototype.log2 = function () {
console.log(this.b)
}
a.log2();
// 2
b.log2();
// 2
通過訪問constructor就可以了。或者我想知道a的構(gòu)造函數(shù)有幾個參數(shù)?
a.constructor.length
或者再復(fù)雜點,我想知道a的構(gòu)造函數(shù)的參數(shù)名是什么(angular的依賴注入就是通過此方法實現(xiàn)的據(jù)說)
a.constructor
.toString()
.match(/(.*)/)
.pop().slice(1,-1)
.split(',');
// ["arg1", "arg2"]
原文:https://segmentfault.com/q/1010000000347868
總結(jié)
以上是生活随笔為你收集整理的js中的constructor的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python模块之pickle(列表,字
- 下一篇: path、classpath理解