【问题标题】:javascript - class with data how to loadjavascript - 带有数据的类如何加载
【发布时间】:2015-04-16 04:44:32
【问题描述】:

我正在尝试用 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错了?

【问题讨论】:

标签: javascript node.js


【解决方案1】:

你会在 OOP 中表现如何?

您可能会有以下选择:

  • 通过 setter(你已经有了 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;
}

【讨论】:

    【解决方案2】:

    一种方法是:

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

    还有其他方法……

    【讨论】:

    • 请不要发布重复的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2015-08-12
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多