日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript:constructor属性

發布時間:2023/12/10 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript:constructor属性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

constructor屬性始終指向創建當前對象的構造函數。比如下面例子:

?

// 等價于 var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
console.log(arr.constructor
=== Array); // true

// 等價于 var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor
=== Function); // true

// 由構造函數實例化一個obj對象
var obj = new Foo();
console.log(obj.constructor
=== Foo); // true
//
將上面兩段代碼合起來,就得到下面的結論
console.log(obj.constructor.constructor === Function); // true

?

?

?

但是當constructor遇到prototype時,有趣的事情就發生了。

我們知道每個函數都有一個默認的屬性prototype,而這個prototype的constructor默認指向這個函數。如下例所示:

function Person(name) {
this.name = name;
};
Person.prototype.getName
= function() {
return this.name;
};
var p = new Person("ZhangSan");
console.log(p.constructor
=== Person); // true
console.log(Person.prototype.constructor === Person); // true
//
將上兩行代碼合并就得到如下結果
console.log(p.constructor.prototype.constructor === Person); // true

?

?

當時當我們重新定義函數的prototype時(注意:和上例的區別,這里不是修改而是覆蓋),constructor屬性的行為就有點奇怪了,如下示例:

function Person(name) {
this.name = name;
};
Person.prototype
= {
getName:
function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor
=== Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false

?

為什么呢?

原來是因為覆蓋Person.prototype時,等價于進行如下代碼操作:

Person.prototype = new Object({
getName:
function() {
return this.name;
}
});

?

而constructor屬性始終指向創建自身的構造函數,所以此時Person.prototype.constructor === Object,即是:

function Person(name) {
this.name = name;
};
Person.prototype
= {
getName:
function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor
=== Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true

怎么修正這種問題呢?方法也很簡單,重新覆蓋Person.prototype.constructor即可:

?

function Person(name) {
this.name = name;
};
Person.prototype
= new Object({
getName:
function() {
return this.name;
}
});
Person.prototype.constructor
= Person;
var p = new Person("ZhangSan");
console.log(p.constructor
=== Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true

?

?

[注:轉帖自http://developer.51cto.com/art/200907/134913.htm]

轉載于:https://www.cnblogs.com/siceblue/archive/2010/03/03/1677306.html

總結

以上是生活随笔為你收集整理的JavaScript:constructor属性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。