我正在研究 Flannagan 的《Javascript:权威指南》。有一节解释了如何通过添加新方法来增强 Javascript 类。示例脚本展示了如何将新方法“Times”添加到数字原型(prototype)中(这就是我解释它的方式)。
我很难知道以下脚本中的参数是什么,特别是“上下文”。
// Invoke the function f this many times, passing the iteration number
// For example, to print "hello" 3 times:
// var n = 3;
// n.times(function(n) { console.log("hello"); });
Number.prototype.times = function(f, context) {
var n = this.valueOf();
console.log(n);
for(var i = 0; i < n; i++) f.call(context, i);
};
var n = 3;
n.times(function(n) { console.log("hello"); });
我认为 f 的值变为:
function(n) { console.log("hello"); })
我不确定“上下文”是什么?
非常感谢您的帮助...
最佳答案
times
接受一个函数; context
参数允许您指定值 this
如果需要的话,指的是该函数内部。
在您的示例中,回调传递给 times
不使用this
根本不需要,但想象一下回调是否依赖于 this
引用一个对象:
const obj = {
count: 3,
increment: function() {
this.count++;
console.log(this.count);
}
};
obj.increment();
obj.increment();
obj.increment
功能取决于obj.count
。为了让它在你的 times
中工作功能,你需要 this
引用obj
,因此将其作为第二个参数传递给 times
,这样 obj
作为第一个参数传递给 .call
:
Number.prototype.times = function(f, context) {
var n = this.valueOf();
console.log('repeating ' + n + ' times:');
for(var i = 0; i < n; i++) f.call(context, i);
};
const obj = {
count: 3,
increment: function() {
this.count++;
console.log(this.count);
}
};
(3).times(obj.increment, obj);
定制this
如果您将不同函数传递给.times
,则不需要,调用 obj.increment
的一个本身:
Number.prototype.times = function(f, context) {
var n = this.valueOf();
console.log('repeating ' + n + ' times:');
for(var i = 0; i < n; i++) f.call(context, i);
};
const obj = {
count: 3,
increment: function() {
this.count++;
console.log(this.count);
}
};
(3).times(() => obj.increment());
关于javascript - 关于 JS 脚本参数的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265790/