相关疑难解决方法(0)

如何在回调中访问正确的`this`?

我有一个构造函数,它注册一个事件处理程序:

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 callback this

1309
推荐指数
12
解决办法
36万
查看次数

箭头函数与函数声明/表达式:它们是等效/可交换的吗?

规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.

ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?

例子:

构造函数

function User(name) {
  this.name = name;
}

// vs

const User = name => {
  this.name = name;
};
Run Code Online (Sandbox Code Playgroud)

原型方法

User.prototype.getName = function() {
  return this.name;
};

// vs

User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)

对象(文字)方法

const obj = {
  getName: function() {
    // ...
  }
};

// vs

const obj = {
  getName: () => {
    // ...
  }
};
Run Code Online (Sandbox Code Playgroud)

回调

setTimeout(function() {
  // ...
}, 500);

// vs

setTimeout(() => {
  // ...
}, …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 arrow-functions

449
推荐指数
2
解决办法
12万
查看次数

ES6对象中的方法:使用箭头函数

在ES6中,这两个都是合法的:

var chopper = {
    owner: 'Zed',
    getOwner: function() { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)

并且,作为速记:

var chopper = {
    owner: 'Zed',
    getOwner() { return this.owner; }
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用新的箭头功能?在尝试类似的东西

var chopper = {
    owner: 'John',
    getOwner: () => { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)

要么

var chopper = {
    owner: 'John',
    getOwner: () => (this.owner)
};
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息,提示该方法无权访问this.这只是一个语法问题,还是你不能在ES6对象中使用fat-pipe方法?

javascript ecmascript-harmony ecmascript-6

70
推荐指数
3
解决办法
2万
查看次数