对象方法与JavaScript中的函数和封装

时间:2015-01-18 18:14:15

标签: javascript node.js

在基于类的面向对象语言中,对象的一个​​好处是封装:对象的每个方法都可以访问对象的数据。

在JavaScript中,由于this的功能,封装的好处似乎并不相同。

在下面的示例中,method1可以访问this而无需额外绑定,但method2没有。

如果我们需要bind method2function2才能访问{{},是否有任何理由在下面的示例中使用对象方法而不是普通函数1}}在他们里面?

this.args

1 个答案:

答案 0 :(得分:1)

我认为你应该总是使用方法而不是使用bind(this),因为当你使用外部函数时,你需要携带那些类。为什么不把它们作为一种方法包含在课堂上呢?

另外,我不明白this.method2.bind(this)电话。 this.method2已绑定到this,因为它是this的属性。

假设您从let语句中了解了一些ES6,您可以编写如下代码:

class Service {
  constructor(args) {
    this.args = args;
  }
  method1(query) {
    let res1 = Service2.get(query).map(this.method2); //btw, what is Service2 here? Is it just an object with methods or does it need to be initialized?
  }
  method2(data) {
    //use data
  }
}
let service = new Service(args);
service.method1(req.query);