Javascript 为什么这不是在使用承诺时给出正确的上下文?
我需要使用Promise在下面的代码中按顺序执行事情。我实际保存的是ajaxpost,我只想在成功发布后调用execute。 一切正常,但问题是我无法访问执行函数中的实际this变量。console.log(this.abc);给了我不确定的原因Javascript 为什么这不是在使用承诺时给出正确的上下文?,javascript,design-patterns,promise,Javascript,Design Patterns,Promise,我需要使用Promise在下面的代码中按顺序执行事情。我实际保存的是ajaxpost,我只想在成功发布后调用execute。 一切正常,但问题是我无法访问执行函数中的实际this变量。console.log(this.abc);给了我不确定的原因 function MyClass(context) { this.abc = "xyz"; }; MyClass.prototype.save = function() { console.log(" saving"
function MyClass(context) {
this.abc = "xyz";
};
MyClass.prototype.save = function() {
console.log(" saving");
return new Promise(function(resolve, reject){
resolve();
});
};
MyClass.prototype.execute = function() {
console.log(" executing");
console.log(this.abc);
};
var myInstance = new MyClass();
window.addEventListener('keydown', function(e) {
e.preventDefault();
if(event.ctrlKey & (event.which==83)) {
myInstance.save();
} else if (event.ctrlKey && (event.which==69)) {
myInstance.save().then(myInstance.execute);
}
}, false);
因为您正在传递一个对要由其他代码执行的函数的引用,而没有指定作为
this
使用的内容
而不是
myInstance.save().then(myInstance.execute);
你能行
myInstance.save().then(function() { myInstance.execute() });
因为在这种情况下,使用点表示法调用execute
,这意味着点左侧的对象将用作this
(myInstance
)
你也可以使用
教训是,重要的是如何调用函数,它可能是:
var a = {
prop: 1,
b: function() {
console.log(this.prop);
}
};
点符号
松散函数调用
使用或
自己绑定此
感谢@JuanMendes它起作用了,有什么技术术语可以描述这种差异吗?不是100%确定,但技术上可以描述为“this的调用时间绑定”。我知道将传递哪个上下文,但仍然无法理解apply和call的用法。在我们的例子中,什么是有趣的和这个参数呢?我的意思是说为什么
myInstance.save().then(myInstance.execute.call(myInstance))代码>不起作用?这是因为您正在立即调用它,而不是向函数传递引用,就像您正在执行。然后(myInstance())
var a = {
prop: 1,
b: function() {
console.log(this.prop);
}
};
// `this` will be `a`, logs 1
a.b();
// If in strict mode, `this` will be undefined, and it will throw an error
// otherwise `this` will be the global object and it will log undefined
var b = a.b;
b();
var b = a.b;
// Call b passing a as `this` and 2 as its argument which is ignored
// Logs 1
b.call(a, 2);
var b = a.b.bind(a);
// b has been bound to a, it will correctly output 1
b();
// Even if you try to use another this
b.call({prop: 2}); // Still logs 1