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

标签 javascript node.js

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

在 JavaScript 中,由于 this 的特性,这种封装的好处似乎并不相同。

在下面的示例中,method1 无需额外绑定(bind)即可访问 this,但 method2 不能。

如果我们需要 bind method2function2,是否有任何理由在下面的示例中使用对象方法而不是普通函数> 为了访问其中的 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/

相关文章:

javascript - 使用 javascript 和 json 加载表格时如何为按钮分配多个值

javascript - 在 iOS/android 上触发触摸标注

javascript - 如何将数据保存在onchange脚本的html中?

node.js - 当我使用 sequelize cli 做所有种子时,但它返回错误 : invalid data?

javascript - 如何从 MongoDB 中的嵌套 find() 将对象数组设置回迭代集合?

javascript - promise xml2js 解析功能(ES6 promise )

javascript - 为什么单击事件和触发单击的事件对象不同?

javascript - 将文本区域数据发送到数据库时出现问题

node.js - Node/Mongo 无法通过 ObjectId 找到

node.js - 来自 Angular ngResource-Service 的 REST-API 调用未由反向代理转发