我有一个构造函数,它注册一个事件处理程序:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);Run Code Online (Sandbox Code Playgroud)
但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.
我还尝试使用对象方法而不是匿名函数:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)
但它表现出同样的问题.
如何访问正确的对象?
假设我有一个基本的哑巴javascript类:
var FunctionX = function(configs) {
this.funcConfigs = configs;
}
FunctionX.prototype.getData = function() {
return $.get('/url');
}
FunctionX.prototype.show = function(promise) {
console.log(this.funcConfigs); // <-- this here is the promise itself, I'm looking to get the instance's configs
}
FunctionX.prototype.setup = function() {
this.GetData().then(show);
}
var f = new FunctionX({ "a": "b" });
f.setup();
Run Code Online (Sandbox Code Playgroud)
现在我在show函数中尝试访问实例变量"funcConfig"."这"是承诺,"funcConfigs"直接返回undefined.
我尝试用a来解决这个问题,.resolveWith(this)但它没有解决这个问题.
如何在此范围上下文中访问实例变量?
我有一个函数调用placeDecode,它接受一个HTML输入元素.在函数中,我有一个将输入值转换为格式化地址的promise.
我打了placeDecode两次电话,检查两个调用时是否已经解析我使用Promise.all,检查每个函数调用.当我尝试调用函数时出现问题viewResult,我得到Cannot read property 'viewresult' of undefined错误.
//call function twice
var startAddress = this.placeDecode1(this.searches.startSearch);
var endAddress = this.placeDecode1(this.searches.endSearch);
//promise all
Promise.all([endAddress,startAddress]).then(function(values) {
this.viewResult(values);
}).catch(function(result){
console.log(result);
})
console.log('hit');
}
//method convertes input into formatted address
private placeDecode1(input: HTMLInputElement) {
var result = new Promise(function(resolve, reject) {
var location = input.value;
var geoCode = new google.maps.Geocoder();
geoCode.geocode({
address: location
}, function(result,status){
if(status == 'OK'){
console.log(result[0].formatted_address);
resolve(result[0].formatted_address);
}
})
});
return result;
} …Run Code Online (Sandbox Code Playgroud)