访问JS私有方法 [英] Accessing JS Private Methods
本文介绍了访问JS私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力使一个JS对象和访问私有方法。尝试返回函数时遇到的问题是私有方法无法访问。
I am working on trying to make an JS object and access to private methods. The problem I am running into when trying to return a function is the private methods cannot be accessed. Code Below.
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());
使用此设置,如何访问私有方法?
With this setup, how can I access the private methods?
推荐答案
我不认为这种模式会对你想做的事情起作用。我认为使用这样的模式会使您的代码更小,更可重用。这样你也可以摆脱设置
函数。
I don't think that pattern will work for what you're trying to do. I think using a pattern like this one will keep your code smaller and more reusable. This way you also get rid of the set
functions.
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());
这篇关于访问JS私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文