javascript - JS中对象的constructor属性
伊谢尔伦
伊谢尔伦 2017-04-11 11:15:59
0
3
688

今天在看JavaScript面向对象编程指南(第二版)的第五章原型的时候,在书中有这么一段话:

function Gadget(name, color) {
  this.name = name;
  this.color = color;
  this.whatAreYou = function() {
    return 'I am a ' + this.color + ' ' + this.name;
  }
}
Gadget.prototype = {
  price: 100,
  rating: 3,
  getInfo: function() {
    return 'Rating: ' + this.rating + ', price: ' + this.price;
  }
}
var newtoy = new Gadget('webcam', 'black');

当我们访问newtoy.rating的时候,JavaScript引擎依然会查询newtoy对象的所有属性,但这次它找不到一个叫rating的属性了,接下来,脚本引擎就会去查询用于创建当前对象的构造函数的原型(等价于我们直接访问newtoy.construtor.prototype).

请注意上段文字斜体加粗的部分:
我在浏览器中执行测结果是

这说明上段加粗斜体文字应该改成:等价于我们直接访问Gadget.prototype

贴出来一是想求证一下,二是想问问对象的construtor属性?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
洪涛

使用对象字面量赋值,导致 Gadget.prototype 被重写了。

Gadget.prototype.rating = 3 
newtoy.constructor == Gadget // true

Gadget.prototype = { rating: 3 }
newtoy.constructor == Gadget // false
迷茫

好像没听说过construtor属性

左手右手慢动作
Gadget.prototype = {
  price: 100,
  rating: 3,
  getInfo: function() {
    return 'Rating: ' + this.rating + ', price: ' + this.price;
  }
}
上面导致了Gadget导致了Gadeget.prototype属性被重写了,所以你在实例化的时候,newtoy的原型上将不再有construtor这个属性;
 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!