繁体   English   中英

从同一对象内的另一个函数引用一个对象内的函数。 JavaScript对象文字形式

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM