简体   繁体   中英

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.

I guess, its the last line of the code 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?

Your problem is where you are trying to call this.promptUpdater() , this isn't what you think it is. this is scoped to the current function, which is your function(resolve, reject) , not your object.

Traditional function method with .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:

To change userInputOn to bind it's this to it's parent's 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.

Here's a fiddle:" https://jsfiddle.net/jmbldwn/fpa9xzw0/5/

This is an issue with the this reference getting "lost" inside the Promise's callback function. There are a number of fixes, but the easiest as of ES6 is to use an arrow function instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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