简体   繁体   English

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

[英]Reference a function inside an object from another function inside the same object. JavaScript object literal form

In the code below when I try to call promptUpdater function from inside userInputOn function in the ArrayRotation object, I get a TypeError: Cannot read property promptUpdater of undefined. 在下面当我尝试调用代码promptUpdater从内部功能userInputOn在功能ArrayRotation对象,我得到一个类型错误:无法读取的未定义的属性promptUpdater。

I guess, its the last line of the code rotationTaskObj.userInputOn(); 我猜,这是代码rotationTaskObj.userInputOn();的最后一行rotationTaskObj.userInputOn(); where I need to correct reference, but I am not able to do it. 我需要更正参考文献的地方,但是我做不到。

'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?

What is the correct way to reference promptUpdater function? 引用promptUpdater功能的正确方法是什么?

Your problem is where you are trying to call this.promptUpdater() , this isn't what you think it is. 您的问题是您试图调用this.promptUpdater()this不是您想的那样。 this is scoped to the current function, which is your function(resolve, reject) , not your object. this仅限于当前函数,即您的function(resolve, reject) ,而不是您的对象。

Traditional function method with .bind .bind传统函数方法

If you don't want to use arrow functions (you should, but I won't judge :-)), you can set a function's this value using the bind() method: 如果您不想使用箭头函数(应该,但是我不会判断:-),则可以使用bind()方法设置函数的this值:

To change userInputOn to bind it's this to it's parent's this : 更改userInputOn使其绑定到父级this

   userInputOn : function() {
       return new Promise(function(resolve, reject) {
           this.promptUpdater(); //correct way to reference promptUpdater fn?
       }.bind(this));
   },

Arrow function method 箭头功能法

Change 更改

 return new Promise(function(resolve, reject) {

To

 return new Promise((resolve, reject) => {

Arrow functions don't have a this like normal functions, they pick up the this from the hosting function. 箭功能没有this像正常的功能,他们拿起this从主存功能。

Here's a fiddle:" https://jsfiddle.net/jmbldwn/fpa9xzw0/5/ 这是一个小提琴:“ https://jsfiddle.net/jmbldwn/fpa9xzw0/5/

This is an issue with the this reference getting "lost" inside the Promise's callback function. 这是在Promise的回调函数中this引用“丢失”的问题。 There are a number of fixes, but the easiest as of ES6 is to use an arrow function instead: 有许多修复程序,但是从ES6开始,最简单的方法是使用箭头功能:

new Promise ((resolve, reject) => {this.promptUpdateUser();})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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