Javascript OO键值对访问器

时间:2014-08-06 13:53:35

标签: javascript oop

在访问JS对象中的keyvalue对时遇到问题,在chrome中出现以下错误:

  

未捕获的TypeError:undefined不是函数   jQuery.event.dispatch jquery-2.1.0.js:4371   jQuery.event.add.elemData.handle

所以,这是我的代码:

//Separate file named Product.js

function Product() {

    var field = {
        ProductName: "False Teeth",
        SupplierID: 7,
    }

    this.init = function () {
        //any initialisation code
    }

    var getProperty = function (propertyName) {
        return field[propertyName];
    }
};


//In another javascript file, trying to access the object

var product = new Product();

//THIS GIVES THE ERROR undefined is not a function
console.log("supplierID:" + product.getProperty("SupplierID")); 

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用:

//Separate file named Product.js

function Product() {

    var field = {
        ProductName: "False Teeth",
        SupplierID: 7,
    }

    this.init = function () {
        //any initialisation code
    }

    this.getProperty = function (propertyName) {
        return field[propertyName];
    }
};


//In another javascript file, trying to access the object

var product = new Product();

//THIS GIVES THE ERROR undefined is not a function
console.log("supplierID:" + product.getProperty("SupplierID"));