我在使用 Ionic 2 时遇到问题,尤其是 Angular 方面的问题。我的问题是我有一个名为“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);
}
}
最佳答案
您应该使用arrow functions ,像这样:
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
属性)。
关于javascript - Ionic 2公共(public)变量和内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700689/