离子2公共变量和内部函数

时间:2017-06-22 13:23:29

标签: javascript function angular typescript ionic2

我遇到了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);
  }
}

1 个答案:

答案 0 :(得分:0)

您应该使用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属性)。