我正在尝试创建一个 JS 对象并访问私有(private)方法。我在尝试返回函数时遇到的问题是无法访问私有(private)方法。代码如下。
var Item = (function() {
var price = 0;
var name = '';
var description = '';
var quantity = '';
var attributes = {};
var Item = function(data) {
}
function setPrice(variable) {
this.price = variable;
};
function getPrice() {
return this.price;
};
function setName(variable) {
this.name = variable;
};
function getName() {
return this.name;
};
function setDescription(variable) {
this.description = variable;
};
function setQuantity(variable) {
this.quanity = variable;
};
return function(data){
setPrice : setPrice;
getPrice : getPrice;
setName : setName;
setDescription : setDescription;
setQuantity : setQuantity;
return new Item(data);
}
})();
item2 = Item();
item2.setPrice('3');
alert(item2.getPrice());
通过此设置,我如何访问私有(private)方法?
最佳答案
我认为该模式不适用于您想要做的事情。我认为使用这样的模式将使您的代码更小并且更可重用。这样您还可以摆脱 set
函数。
var Item = function(options) {
var opts = $.extend({
price: 0,
name: '',
description: '',
quantity: '',
attributes: {}
}, options);
// ...
this.getPrice = function() {
return opts.price;
};
// ...
};
var item = new Item({
price: 100,
name: 'onehundred',
// ...
});
alert(item.getPrice());
关于javascript - 访问 JS 私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595285/