函数是 JavaScript 中的“函数”对象吗?如果是这样,当我创建一个构造函数时,例如:
//this is a constructor function
function foo(){
this.name="xx";
}
foo 是否有一个名为 proto 的属性,指向该函数的原型(prototype)?我怎样才能看到这个属性?
ps:如果通过new
关键字创建实例时创建了proto,为什么function foo
没有它呢?根据上面的内容,foo
是通过new Function
创建的。
最佳答案
is function a object in javascript?
是的。
Does foo has a property named proto pointing to the Function 's prototype?
未命名proto
,不。这是一个有点令人困惑的区域:
所有对象都有一个它们继承的底层原型(prototype)对象。从 ES5 开始,您可以通过
Object.getPrototypeOf
获取对该对象的引用(例如,var p = Object.getPrototypeOf(blah)
为您提供对blah
的原型(prototype))。 一些引擎(包括 Firefox 的 SpiderMonkey)还通过伪属性__proto__
提供底层原型(prototype),这将是 in the spec as of ES6 ,但官方only when JavaScript is used in browsers .另外,所有普通函数都有一个名为
prototype
的属性,它不是该函数的底层原型(prototype)(见上文)。相反,该对象将被分配为通过new
关键字使用该函数作为构造函数创建的对象的底层原型(prototype)。
既然这有点困惑,我们画一张图吧。假设我们有这样的代码:
function Foo() {
this.name = "xx";
}
var f = new Foo();
(因为我将它用作构造函数,所以我使用名称 Foo
而不是 foo
来遵守约定。)
这是我们现在内存中的内容:
+------------+ | Function | | (function) | +------------+ +-----------+ | __proto__ |----+->| (object) | This is the object assigned to functions | prototype |----/ +-----------+ as their underyling prototype +------------+ | | call | | | apply | | | bind | | | ... | | +-----------+ +------------+ | | Foo | | | (function) | | +------------+ | | __proto__ |----+ | | +----------+ | prototype |----+---->| (object) | This is the object assigned to +------------+ | +----------+ objects created via `new Foo` | | (blank) | | +----------+ +-----------+ | | f | | | (object) | | +-----------+ | | __proto__ |-----+ | name: xx | +-----------+
(I've left off the references to Object.property
above to keep things simpler.)
How can I see this property.
See above, either __proto__
(on only some engines for now, will be standard in ES6) or via Object.getPrototypeOf
(ES5).
Example:
// Shows you the object referenced by Function.prototype,
// which is `foo`'s underyling prototype
// ONLY WORKS ON SOME ENGINES for now (including Firefox's SpiderMonkey)
console.log(foo.__proto__);
// Shows you the object referenced by foo.prototype
console.log(foo.prototype);
关于javascript - JavaScript 中的函数是对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339346/