ts类中,箭头函数和普通函数的区别?


class Queue<T> {
  private data: T[] = [];
  push1 = (item: T) => {
    console.log(1,this)
    this.data.push(item)
  };
  push(item: T) {
    console.log(2, this)
    this.data.push(item)
  }
}

// 简单的使用

const queue = new Queue<number>();
queue.push(0);
queue.push1(1)

打印结果:

image.png

编译结果:


var Queue = /** @class */ (function () {
    function Queue() {
        var _this = this;
        this.data = [];
        this.push1 = function (item) {
            console.log(1, _this);
            _this.data.push(item);
        };
    }
    Queue.prototype.push = function (item) {
        console.log(2, this);
        this.data.push(item);
    };
    return Queue;
}());
// 简单的使用
var queue = new Queue();
queue.push(0);
queue.push1(1);

这两种方法有什么本质的区别吗

阅读 3.6k
2 个回答

一个在原型链上、一个不在。

你要是没有继承的话两者就没区别。

P.S. 这跟 TS 无关,ES6 的 class 就是这样工作的。

这不是看到结果了么,就是用来绑定scope的

class Foo{
    constructor() {
        setTimeout(this.bar, 0);
        setTimeout(this.barArrow, 0);
    }

    bar() {
        console.log("bar", this);
    }

    barArrow = () => {
        console.log("bararrow", this);
    }
}

new Foo();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题