Javascript:函数与函数的区别。原型
Javascript : Difference between Function and Function. Prototype
如果我们创建一个像这样的函数:
function Rabbit() {}
我们看到它继承自 Function
继承自的同一个对象,即
Rabbit.__proto__ === Function.__proto__
这个更高的对象是什么?如果我们尝试记录它,它看起来像:ƒ () { [native code] }
。 Rabbit
不应该继承自 Function
对象因为它是一个函数吗?有人可以解释我错在哪里吗?
What is this higher object?
是Function.prototype
引用的对象,is also a function。这是函数从 (call
、apply
、bind
、name
和 length
).
获取属性和方法的地方
那个对象的原型是由Object.prototype
引用的the object,负责hasOwnProperty
和toString
并且,由于您在示例中使用了它,因此 __proto__
(这是一个仅用于向后兼容的 Web 功能;不要使用它,请改用 Object.getPrototypeOf
)。
Shouldn't Rabbit
be inheriting from Function
object because it's a function?
不,那是 Function.prototype
的目的。
让我们暂时搁置 Function
。假设你有:
function Thingy() {
}
和
let t = new Thingy();
Object.getPrototypeof(t) === Thingy.prototype
将为真,因为当您使用 new Thingy
时,生成的对象获取 Thingy.prototype
指向的对象作为其原型。这就是构造函数和原型在 JavaScript.
中的工作方式
Function
是创建函数的构造函数。所以等价的是:
let Rabbit = new Function();
Object.getPrototypeOf(Rabbit) === Function.prototype
是真的。对于那些不是通过 new Function
.
创建的函数,如 Rabbit
,也是如此
Shouldn't Rabbit be inheriting from Function object because it's a function?
不,因为它是一个常规函数。您以这种方式创建的每个函数实际上都是一个 Function
对象实例。参见 mdn。
为了使 Function
成为对象的原型,您需要将其明确指定为对象的原型并使用 new
关键字创建实例。
如果我们创建一个像这样的函数:
function Rabbit() {}
我们看到它继承自 Function
继承自的同一个对象,即
Rabbit.__proto__ === Function.__proto__
这个更高的对象是什么?如果我们尝试记录它,它看起来像:ƒ () { [native code] }
。 Rabbit
不应该继承自 Function
对象因为它是一个函数吗?有人可以解释我错在哪里吗?
What is this higher object?
是Function.prototype
引用的对象,is also a function。这是函数从 (call
、apply
、bind
、name
和 length
).
那个对象的原型是由Object.prototype
引用的the object,负责hasOwnProperty
和toString
并且,由于您在示例中使用了它,因此 __proto__
(这是一个仅用于向后兼容的 Web 功能;不要使用它,请改用 Object.getPrototypeOf
)。
Shouldn't
Rabbit
be inheriting fromFunction
object because it's a function?
不,那是 Function.prototype
的目的。
让我们暂时搁置 Function
。假设你有:
function Thingy() {
}
和
let t = new Thingy();
Object.getPrototypeof(t) === Thingy.prototype
将为真,因为当您使用 new Thingy
时,生成的对象获取 Thingy.prototype
指向的对象作为其原型。这就是构造函数和原型在 JavaScript.
Function
是创建函数的构造函数。所以等价的是:
let Rabbit = new Function();
Object.getPrototypeOf(Rabbit) === Function.prototype
是真的。对于那些不是通过 new Function
.
Rabbit
,也是如此
Shouldn't Rabbit be inheriting from Function object because it's a function?
不,因为它是一个常规函数。您以这种方式创建的每个函数实际上都是一个 Function
对象实例。参见 mdn。
为了使 Function
成为对象的原型,您需要将其明确指定为对象的原型并使用 new
关键字创建实例。