[英]Reference a function inside an object from another function inside the same object. JavaScript object literal form
在下面当我尝试调用代码promptUpdater
从内部功能userInputOn
在功能ArrayRotation
对象,我得到一个类型错误:无法读取的未定义的属性promptUpdater。
我猜,这是代码rotationTaskObj.userInputOn();
的最后一行rotationTaskObj.userInputOn();
我需要更正参考文献的地方,但是我做不到。
'use strict';
var ArrayRotation = {
arr : [],
promptUpdater : function() {
//code
},
userInputOn : function() {
return new Promise(function(resolve, reject) {
this.promptUpdater(); //correct way to reference promptUpdater fn?
});
},
}
let rotationTaskObj = Object.create(ArrayRotation);
let userInputPr = rotationTaskObj.userInputOn(); //My guess, I need to create correct refernce here, not able to get how to do that?
引用promptUpdater
功能的正确方法是什么?
您的问题是您试图调用this.promptUpdater()
, this
不是您想的那样。 this
仅限于当前函数,即您的function(resolve, reject)
,而不是您的对象。
.bind
传统函数方法
如果您不想使用箭头函数(应该,但是我不会判断:-),则可以使用bind()
方法设置函数的this
值:
更改userInputOn
使其绑定到父级this
:
userInputOn : function() {
return new Promise(function(resolve, reject) {
this.promptUpdater(); //correct way to reference promptUpdater fn?
}.bind(this));
},
箭头功能法
更改
return new Promise(function(resolve, reject) {
至
return new Promise((resolve, reject) => {
箭功能没有this
像正常的功能,他们拿起this
从主存功能。
这是一个小提琴:“ https://jsfiddle.net/jmbldwn/fpa9xzw0/5/
这是在Promise的回调函数中this
引用“丢失”的问题。 有许多修复程序,但是从ES6开始,最简单的方法是使用箭头功能:
new Promise ((resolve, reject) => {this.promptUpdateUser();})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.