对象方法与JavaScript中的函数和封装
在基于类的面向对象的语言中,对象的好处之一就是封装:对象的每个方法都可以访问对象的数据。
在JavaScript中,封装的这个好处似乎并不相同,因为这个特性。
在下面的例子中, method1
可以在没有附加绑定的情况下访问this
,但method2
不能。
如果我们需要bind
method2
和function2
以访问内部的this.args
, 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
已经绑定到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);