function Person(name) {
this.name = name;
}
var rob = new Person('Rob');
- 人是一个函数。
- 人是一个对象。
- 人不是人。
- rob 是一个对象。
- rob 的原型(prototype) (
__proto__
) 是 Person.prototype,所以 rob 是一个 Person。
但是
console.log(Person.prototype);
输出
Person {}
Person.prototype 是一个对象吗?大批?一个人?
如果是Object,那个原型(prototype)是不是也有原型(prototype)?
更新我从这个问题中学到的知识(2014 年 1 月 24 日,星期五,上午 11:38:26)
function Person(name) {
this.name = name;
}
var rob = new Person('Rob');
// Person.prototype references the object that will be the actual prototype (x.__proto__)
// for any object created using "x = new Person()". The same goes for Object. This is what
// Person and Object's prototype looks like.
console.log(Person.prototype); // Person {}
console.log(Object.prototype); // Object {}
console.log(rob.__proto__); // Person {}
console.log(rob.__proto__.__proto__); // Object {}
console.log(typeof rob); // object
console.log(rob instanceof Person); // true, because rob.__proto__ == Person.prototype
console.log(rob instanceof Object); // true, because rob.__proto__.__proto__ == Object.prototype
console.log(typeof rob.__proto__); // object
console.log(rob.__proto__ instanceof Person); // false
console.log(rob.__proto__ instanceof Object); // true, because rob.__proto__.__proto__ == Object.prototype
- 原型(prototype)只是普通对象。
- typeof 可用于确定某物是对象还是原始类型(以及它是哪种类型的原始类型),但对于确定它是哪种类型的对象毫无用处。
- LHS instanceof RHS 如果 RHS.prototype 出现在 LHS 原型(prototype)链的某处,则返回 true。
最佳答案
Is Person.prototype an object?
是的。所有(有趣的) 都是一个对象:-)参见How is almost everything in Javascript an object?了解详情。
An Array?
不,绝对不是。
A Person?
视情况而定。大多数人会说它不是 Person
的一个实例——它是所有 Person 的本质(它们的原型(prototype) :-)。但是,console.log
似乎将其标识为这样,因为它有一个指向 Person
构造函数的 .constructor
属性。
If it is an Object, does that prototype also have a prototype?
是的。每个对象都有一个原型(prototype)。这些构建了所谓的原型(prototype)链,其末端是一个null
引用。在您的特定示例中,它是
rob
|
v
Person.prototype
|
v
Object.prototype
|
v
null
关于javascript - 什么类型的对象是 Javascript 原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21299416/