javascript – 类与数据如何加载

我试图在JavaScript中build模一个产品:

var Product = {}; Product.getSku = function() { return this.sku; } Product.getPrice = function() { return this.price } Product.getName = function() { return this.name } module.exports = Product; 

用所需的属性创build这个对象的正确方法是什么?

我来自oop背景,我在想js错了吗?

你会怎么做在面向对象?

你可能会有这些select:

  • 通过setters(你已经有getters)。
  • 通过构造函数。
  • 直接通过字段。

第一个和最后一个是显而易见的。

在第二个,你可能会做这样的事情:

 var Product = function(sku, price, name) { this.sku = sku; this.price = price; this.name = name; } var product = new Product(1, 2.34, "FiveSix"); 

这种变化是将一个对象作为一个parameter passing的:

 var Product = function(data) { var productData = data || {}; this.sku = productData.sku; this.price = productData.price; this.name = productData.name; } 

一种方法是:

 function Product(name, sku, price){ this.name = name; this.sku = sku; this.price = price; this.getSku = function(){ return this.sku; } this.getPrice = function(){ return this.price } this.getName = function(){ return this.name } } module.exports = new Product("book", "aa123bb456", 6.35); 

还有其他的方法….