国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript類和繼承 constructor屬性

2019-11-21 00:42:23
字體:
來源:轉載
供稿:網友
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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安康市| 浏阳市| 保靖县| 平顶山市| 曲松县| 内丘县| 阿克苏市| 松潘县| 万荣县| 凤台县| 林州市| 罗甸县| 禄丰县| 边坝县| 株洲县| 龙江县| 天长市| 体育| 岳普湖县| 富平县| 沅陵县| 星子县| 淮北市| 永城市| 怀来县| 麻栗坡县| 灵丘县| 嘉义市| 太谷县| 梅河口市| 桓仁| 盱眙县| 茌平县| 西华县| 古交市| 曲靖市| 灌阳县| 静乐县| 东丰县| 浦城县| 潍坊市|