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