我在使用Ionic 2时遇到了问题,尤其是角度。我的问题是我有一个名为"isConnected"的变量,当我想从函数的内部函数访问时,我不能。它说不能定义未定义的属性。如何从内部函数访问我的变量 isConnected?我尝试了这个:BleProvider.prototype.isConnected,但它不起作用。有人可以向我解释这是如何工作的吗?
export class BleProvider {
public isConnected = false;
public mDevice;
constructor(public http: Http) {}
connectToDevice(device){
console.log('Connecting to device...');
this.mDevice = device;
setTimeout(
ble.connectToDevice(
device,
onConnected,
onDisconnected,
onConnectError),
500);
function onConnected(device) {
console.log("Connected to device: " + device.name);
this.isConnected = true;
console.log("isConnected variable status: " + this.isConnected);
}
function onDisconnected(device) {
console.log('Disconnected from device: ' + device.name);
}
function onConnectError(error) {
console.log('Connect error: ' + error);
}
}
你应该使用箭头函数,如下所示:
export class BleProvider {
public isConnected = false;
public mDevice;
constructor(public http: Http) { }
connectToDevice(device) {
console.log('Connecting to device...');
this.mDevice = device;
// Create the callbacks by using arrow functions () => {...}
let onConnected = (device) => {
console.log("Connected to device: " + device.name);
this.isConnected = true;
console.log("isConnected variable status: " + this.isConnected);
},
onDisconnected = (device) => {
console.log('Disconnected from device: ' + device.name);
},
onConnectError = (error) => {
console.log('Connect error: ' + error);
}
// You can also use an arrow function in the setTimeout! :)
setTimeout(() => {
ble.connectToDevice(device, onConnected, onDisconnected, onConnectError);
}, 500);
}
}
使用常规函数时,this
关键字引用函数本身,但在使用箭头函数时,this
属性不会被覆盖,并且仍引用组件实例(在其中定义了 isConnected
属性(。