gpt4 book ai didi

javascript - JS : The Good Parts: The `superior` function

转载 作者:行者123 更新时间:2023-12-03 01:22:32 24 4
gpt4 key购买 nike

我正在尝试理解 Douglas Crockford 的《Javascript:优秀部分》第 1 章“优秀部分”中有关继承的示例。特别是superior功能。书上是这样说的:

Object.method('superior', function(name) {

var that = this, method = that[name];
return function() {
// Why can’t this just be `return method`?
return method.apply(that, arguments);
};
});

正如上面代码注释中提到的,我不明白为什么我们需要使用 apply ,而简单地返回函数本身似乎在我的实验中找到了工作。

补充信息

上面使用的方法函数定义为

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

最佳答案

这确实是一种有点复杂的做事方式。一个可能的优点是生成的函数将自动绑定(bind)到初始 this 上下文(即您随后无需引用实例即可调用它)。

我想下面的实现会更清楚地揭示意图:

Object.method("superior", function(name) {
var that = this, method = that[name];
return method.bind(that);
});

(从下一页的 coolcat 示例中,这种可能的优点并没有直接显现出来,因为 get_name 方法没有使用 this > 上下文。)

关于javascript - JS : The Good Parts: The `superior` function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51702618/

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