gpt4 book ai didi

Javascript:函数.原型(prototype).方法

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:49 24 4
gpt4 key购买 nike

我想你们中的大多数人都看过以下代码片段:

Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};

我也知道它会影响所有函数,因为它们都是由 Function 创建的对象,因此它们可以访问名为“method”的方法,但是我很困惑为什么 Function 本身也可以像下面这样访问“method”:

Function.method('test', function () {return 1;});

最佳答案

Edorka 的回答是正确的:函数是它自己的构造函数(即“父”)。

Function.constructor;  // function Function() { [native code] }

通常你不能做你正在做的事情。例如,这将不起作用:

f = function () {};
f.prototype.a = 5;
f.a; // undefined

这种事情只有在你使用函数作为构造函数时才有效,就像这样:

f = function () {};
f.prototype.a = 5;
g = new f();
g.a; // 5

但 Function 很奇怪,它是所有函数的构造函数,也是一个函数本身,因此它将其属性模板化为它自己的 原型(prototype)。因此,您可以在代码中调用 Function.method()

关于Javascript:函数.原型(prototype).方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17446361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com