Javascript中的新对象是否具有原型属性? [英] Does a new object in Javascript have a prototype property?

查看:78
本文介绍了Javascript中的新对象是否具有原型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对于学术价值来说是一个纯粹的微不足道的问题:

This is a purely trivial question for academic value:

如果我创建一个新对象,可以这样做:

If I create a new object, either by doing:

var o = { x:5, y:6 };

var o = Object.create({ x:5, y:6 });

,我得到 undefined 。我认为任何新创建的对象都会自动继承 Object.prototype 原型。

when I query the o.prototype property, I get undefined. I thought that any newly created object automatically inherits the Object.prototype prototype.

此外,调用 toString(),(此方法为 Object.prototype )在这个对象上运行正常,暗示 o 继承自 Object.prototype 。那么为什么我得到 undefined

Furthermore, invoking toString(), (a method of Object.prototype) on this object works just fine, implying that o does inherit from Object.prototype. So why do I get undefined?

推荐答案

之间有区别实例及其构造函数。

There is a difference between instances and their constructors.

创建像 {a:1} 这样的对象时,您正在创建一个实例对象构造函数。 Object.prototype 确实可用,该原型中的所有函数都可用:

When creating an object like {a: 1}, you're creating an instance of the Object constructor. Object.prototype is indeed available, and all functions inside that prototype are available:

var o = {a: 1};
o.hasOwnProperty === Object.prototype.hasOwnProperty; // true

Object.create 有些不同。它创建一个实例(一个对象),但插入一个额外的原型链:

But Object.create does something different. It creates an instance (an object), but inserts an additional prototype chain:

var o = {a: 1};
var p = Object.create(o);

该链将是:

Object.prototype  -  o  -  p

这意味着:

p.hasOwnProperty === Object.prototype.hasOwnProperty; // true
p.a === o.a; // true

要在实例下获取原型,可以使用 Object.getPrototypeOf

To get the prototype "under" an instance, you can use Object.getPrototypeOf:

var o = {a: 1};
var p = Object.create(o);

Object.getPrototypeOf(p) === o; // true
Object.getPrototypeOf(o) === Object.prototype; // true

(以前,您可以使用 o访问实例的原型。 __proto __ ,但这已被弃用。)

(Previously, you could access an instance's prototype with o.__proto__, but this has been deprecated.)

请注意,您还可以按如下方式访问原型:

Note that you could also access the prototype as follows:

o.constructor === Object; // true

所以:

o.constructor.prototype === Object.prototype // true
o.constructor.prototype === Object.getPrototypeOf(o); // true

Object.create -created对象,因为它们没有构造函数(或者更确切地说,它们的构造函数是 Object 而不是传递给 Object.create 因为没有构造函数。)

This fails for Object.create-created objects because they do not have a constructor (or rather, their constructor is Object and not what you passed to Object.create because the constructor function is absent).

这篇关于Javascript中的新对象是否具有原型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆