将对象的方法传递给 Javascript 中的函数。这是对问题的正确解释吗?
Pass an object's method to a function in Javascript. Is this the correct interpretation of the question?
我在面试的时候,有这个问题:
When the method X of an object O is passed to a function Y as a parameter, what happens if X contains a reference to 'this' and gets executed inside Y? Please provide code examples.
这段代码对问题的解释是否正确?
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
let generic = O.X();
function Y(param) {
return param;
}
console.log(Y(generic));
即使只是举个例子,你能帮我理解并回答这个问题吗?
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
let generic = O.X;
function Y(fn) {
return fn(); // <-- execute here
}
console.log(Y(generic));
题目问的是函数是否传递,而不是函数是否立即调用,然后传递。他们可能在想这样的事情:
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
function callbackInvoker(fn) {
fn();
}
callbackInvoker(O.X);
如您所见,除非传递的方法首先被绑定,或者是箭头函数,否则它对 O
对象的 this
绑定将丢失,这可能是问题所在是想考你一下。
我在面试的时候,有这个问题:
When the method X of an object O is passed to a function Y as a parameter, what happens if X contains a reference to 'this' and gets executed inside Y? Please provide code examples.
这段代码对问题的解释是否正确?
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
let generic = O.X();
function Y(param) {
return param;
}
console.log(Y(generic));
即使只是举个例子,你能帮我理解并回答这个问题吗?
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
let generic = O.X;
function Y(fn) {
return fn(); // <-- execute here
}
console.log(Y(generic));
题目问的是函数是否传递,而不是函数是否立即调用,然后传递。他们可能在想这样的事情:
let O = {
name: 'John',
age: 30,
X() {
console.log(this.name);
},
};
function callbackInvoker(fn) {
fn();
}
callbackInvoker(O.X);
如您所见,除非传递的方法首先被绑定,或者是箭头函数,否则它对 O
对象的 this
绑定将丢失,这可能是问题所在是想考你一下。