简体   繁体   English

Javascript对象的prototype属性

[英]Javascript object's prototype property

I have a question about prototype object. 我对原型对象有疑问。

I learned that constructor function has prototype property (not [[prototype]] property) and it indicates prototype object. 我了解到构造函数具有原型属性(不是[[prototype]]属性),它表示原型对象。

ex) If function's name is Person, prototype object's name will be Person.prototype 例如)如果函数的名称为Person,则原型对象的名称为Person.prototype

So I typed this code below. 所以我在下面输入了这段代码。

function Person(name) {
    this.name = name;
}

var foo = new Person('foo');

console.dir(Person);

If my thought is right, Person function's prototype property has to point Person.prototype but actual result is different. 如果我的想法正确,Person函数的原型属性必须指向Person.prototype,但实际结果会有所不同。

我的浏览器的屏幕截图

But my book says: 但是我的书说:

我的书的照片

Why is Person.prototype's name 'Object' ??? 为什么Person.prototype的名称是“ Object”? I don't know why... My mental is going to be broken... 我不知道为什么...我的头脑会被打破...

Someone please answer.. :( 有人请回答.. :(

Your Person() function has a prototype property. 您的Person()函数具有prototype属性。 Person().prototype is called Object because it is indeed an object. Person().prototype之所以称为Object ,是因为它确实是一个对象。 In console, it is purely saying that the prototype property is an object. 在控制台中,纯粹是说prototype属性是一个对象。

Because of the constructor name, it displays Person, possibly because the author used a different JavaScript/Browser version, or another version entirely. 由于构造函数的名称,它显示Person,可能是因为作者使用了不同的JavaScript /浏览器版本,或完全使用了另一个版本。 The 'Object' that you get is normal, and your code should work normally. 您获得的“对象”是正常的,并且您的代码应正常工作。 You can ignore the difference. 您可以忽略差异。

A function's prototype property is to allow you to add properties to your code. 函数的prototype属性是允许您将属性添加到代码中。 Here is an example: 这是一个例子:

function Person(name, age, id) {
  this.name = name;
  this.age = age;
  this.id = id;
}

var me = new Person("Brian", 12, 0);

Then later on in the code if you want to add a property to the person function, like my favorite programming languages: 然后在代码中稍后,如果您想向person函数添加属性,例如我最喜欢的编程语言:

Person.prototype.favLanguages = null;

When you want to define my favorite languages you can do: 如果要定义我喜欢的语言,可以执行以下操作:

me.favLanguages = ['JavaScript', 'Java', 'HTML', 'CSS'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM