在基于类的面向对象语言中,对象的好处之一是封装:对象的每个方法都可以访问对象的数据。
在 JavaScript 中,由于 this
的特性,这种封装的好处似乎并不相同。
在下面的示例中,method1
无需额外绑定(bind)即可访问 this
,但 method2
不能。
如果我们需要 bind
method2
和 function2
,是否有任何理由在下面的示例中使用对象方法而不是普通函数> 为了访问其中的 this.args
?
// service declaration
function Service(args) {
this.args = args;
}
Service.prototype.method1 = function(query) {
............
let res1 = service2.get(query).map(this.method2.bind(this)); // option 1
let res2 = service2.get(query).map(function2.bind(this)); // option 2
............
};
Service.prototype.method2 = function(data) {
// use args from 'this'
}
function function2(data) {
// use args from 'this'
}
// service use
let service = new Service(args);
service.method1(req.query).
最佳答案
我认为您应该始终使用方法而不是使用 bind(this)
,因为当您使用外部函数时,您需要将它们与该类一起携带。为什么不将它们作为类的方法包括在内?
此外,我不明白 this.method2.bind(this)
调用的意义。 this.method2
已经绑定(bind)到 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);
关于javascript - JavaScript 中的对象方法与函数和封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013097/