簡體   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