我在试验一些例子时遇到了一个问题,如果我们想向原型(prototype)添加一个函数,它将无法访问构造函数的私有(private)成员。我遇到了this解决方案。这似乎是一个不错的技巧。
我尝试了其他一些方法,得到了以下结果:
var Restaurant = function()
{
var myPrivateVar;
var private_stuff = function() // Only visible inside Restaurant()
{
return "I can set this here!";
}
Restaurant.prototype.use_restroom = function() // use_restroom is visible to all
{
private_stuff();
}
Restaurant.prototype.buy_food = function() // buy_food is visible to all
{
return private_stuff();
}
}
var restaurant = new Restaurant();
restaurant.buy_food(); // this would work
restaurant.private_stuff(); // this won't
这个解决方案看起来很奇怪,因为我们在构造函数中添加到原型(prototype)中。 (我还没有看到太多)。它至少适用于 firefox 5 和 chrome。有什么问题吗?
最佳答案
您所做的是在每次创建新餐厅对象时在原型(prototype)上重新定义这些方法。更明智的做法是在 this
上定义它们,这是在构造函数中构造的新对象:
var Restaurant = function()
{
var myPrivateVar;
var private_stuff = function() // Only visible inside Restaurant()
{
return "I can set this here!";
}
this.use_restroom = function() // use_restroom is visible to all
{
private_stuff();
}
this.buy_food = function() // buy_food is visible to all
{
return private_stuff();
}
}
虽然你可以这样做,而不是使用 new
:
var RestaurantMaker = function () {
var myPrivateVar;
var private_stuff = function() {
return "I can set this here!";
}
return {
use_restroom: function () {
private_stuff();
},
buy_food: function () {
return private_stuff();
}
};
}
然后就做:
var restaurant = RestaurantMaker();
这称为揭示模块模式。缺点是每个新对象都会获得所有函数的副本,如果您在构造函数中向 this
添加方法,也会发生这种情况。
显示模块模式的一个非常小的替代版本(我认为读起来更好一些)如下所示:
var RestaurantMaker = function () {
var myPrivateVar;
function private_stuff() {
return "I can set this here!";
}
function use_restroom() {
private_stuff();
}
function buy_food() {
return private_stuff();
}
return {
use_restroom: use_restroom,
buy_food: buy_food
};
}
然后,如果你想改变一个函数是否是私有(private)的,只需在返回的对象中添加或删除它即可。
关于javascript - 在构造函数中向原型(prototype)添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7039020/