對象的constructor屬性用於返回創建該對象的函數,也就是我們常說的構造函數。
在JavaScript中,每個具有原型的對象都會自動獲得constructor屬性。除了arguments、Enumerator、Error、Global、Math、RegExp、Regular Expression等一些特殊對象之外,其他所有的JavaScript內置對象都具備constructor屬性。例如:Array、Boolean、Date、Function、Number、Object、String等。
語法
Object.constructor
返回值
對象的constructor屬性返回創建該對象的函數的引用。
示例&說明
以下代碼中的[native code]
,表示這是JavaScript的底層內部代碼實現,無法顯示代碼細節。
// 字符串:String() var str = "張三"; alert(str.constructor); // function String() { [native code] } alert(str.constructor === String); // true // 數組:Array() var arr = [1, 2, 3]; alert(arr.constructor); // function Array() { [native code] } alert(arr.constructor === Array); // true // 數字:Number() var num = 5; alert(num.constructor); // function Number() { [native code] } alert(num.constructor === Number); // true // 自定義對象:Person() function Person(){ this.name = "CodePlayer"; } var p = new Person(); alert(p.constructor); // function Person(){ this.name = "CodePlayer"; } alert(p.constructor === Person); // true // JSON對象:Object() var o = { "name" : "張三"}; alert(o.constructor); // function Object() { [native code] } alert(o.constructor === Object); // true // 自定義函數:Function() function foo(){ alert("CodePlayer"); } alert(foo.constructor); // function Function() { [native code] } alert(foo.constructor === Function); // true // 函數的原型:bar() function bar(){ alert("CodePlayer"); } alert(bar.prototype.constructor); // function bar(){ alert("CodePlayer"); } alert(bar.prototype.constructor === bar); // true
為了將實例的構造器的原型對象暴露出來, 比如你寫了一個插件,別人得到的都是你實例化后的對象, 如果別人想擴展下對象,就可以用 instance.constructor.prototype 去修改或擴展原型對象
鏈接:https://www.zhihu.com/question/19951896/answer/67551712
引用
javascript 對象中的 constructor屬性的作用?的回答:
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在閉包里,所以現在我們是不能直接訪問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的構造函數有幾個參數?
a.constructor.length
或者再復雜點,我想知道a的構造函數的參數名是什么(angular的依賴注入就是通過此方法實現的據說)
a.constructor .toString() .match(/\(.*\)/) .pop().slice(1,-1) .split(','); // ["arg1", "arg2"]