javascript-如何加载包含数据的类

javascript-如何加载包含数据的类,javascript,node.js,Javascript,Node.js,我正在尝试用javascript为产品建模: var Product = {}; Product.getSku = function() { return this.sku; } Product.getPrice = function() { return this.price } Product.getName = function() { return this.name } module.exports = Product; 使用所需属性创建此对象的正确方法是什么

我正在尝试用javascript为产品建模:

var Product = {};
Product.getSku = function() {
    return this.sku;
}
Product.getPrice = function() {
    return this.price
}
Product.getName = function() {
    return this.name
}
module.exports = Product;
使用所需属性创建此对象的正确方法是什么


我来自oop背景,我认为js错了吗?

在oop中你会怎么做

您可能会有以下选择:

  • 通过setters(您已经有了getter)
  • 通过构造函数
  • 直接通过字段
第一个和最后一个是显而易见的

在第二步中,您可能会执行以下操作:

var Product = function(sku, price, name) {
    this.sku = sku;
    this.price = price;
    this.name = name;
}

var product = new Product(1, 2.34, "FiveSix");
这种方法的一种变体是将对象作为单个参数传递:

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);

还有其他方法

看看这里:可能重复的请不要张贴重复的答案。