【发布时间】:2014-01-04 10:16:35
【问题描述】:
三部分问题:
添加第二层抽象并使用原型 getter/setter 函数调用特权构造函数 getter/setter 函数有什么价值?请参阅下面的
ns.Wheel.prototype.getWeight2()和ns.Wheel.prototype.setWeight2()。对
swiss.getWeight()的调用会调用构造函数中的this.getWeight()方法。有什么方法可以将原型链上移一级以调用ns.Wheel.prototype.getWeight()?将原型 getter/setter 函数“隐藏”在构造函数 getter/setter 之后的任何值?例如,
ns.Wheel.prototype.getWeight()在构造函数中“隐藏”在this.getWeight()方法后面。
还要注意原型 getter/setter 如何为克添加单位;即“g”单位。例如,this.getWeight 返回 1000,而 ns.Wheel.prototype.getWeight 返回 1000g。
本例中使用了瑞士奶酪轮。
(function(ns) {
ns.Wheel = function() {
var _weight = 1000; // weight of cheese wheel. Private variable.
this.getWeight = function() { return _weight } // privileged weight getter
this.setWeight = function(weight) { return _weight = weight } // privileged weight setter
}
ns.Wheel.prototype.getWeight = function() { return this.getWeight()+'g' }
ns.Wheel.prototype.setWeight = function(weight) { return this.setWeight(weight)+'g' }
ns.Wheel.prototype.getWeight2 = function() { return this.getWeight()+'g' }
ns.Wheel.prototype.setWeight2 = function(weight) { return this.setWeight(weight)+'g' }
})(window.cheese = window.cheese || {}); // immediate function namespacing technique
var swiss = new cheese.Wheel();
console.log(swiss.getWeight()); //-> 1000. Invokes constructor method
console.log(swiss.setWeight(2000)); //-> 2000. Invokes constructor method
console.log(swiss._weight); //-> undefined. Private variable!!!
console.log(swiss.getWeight2()); //-> 2000g. Invokes prototype method.
console.log(swiss.setWeight2(9000)); //->9000g. Invokes prototype method.
【问题讨论】:
-
我建议您使用
Class.create和$super()看看prototype.js及其非常好的 inheritance behavour。朋友们,现在因为我复活了这样一个邪恶的老图书馆而将我用石头打死! ;) -
我建议不要担心在 JS 中将变量设为“私有”。为了拥有“私有”变量,您必须将使用它们的方法移动到构造函数中,这意味着您在构造函数中拥有每个非“静态”方法的副本。这是对内存的浪费。一个常见的约定是用下划线命名“私有”变量,然后永远不要在创建它们的上下文之外使用带有下划线前缀的变量。如果您真的想要私有,请考虑使用 TypeScript,它可以执行我的建议,但会在编译时为您检查。
-
我同意 cmets 不使用闭包来拥有“私有”成员和特权方法,但如果你真的必须这样做,那么这种模式可能有用:stackoverflow.com/a/19879651/1641941 它不会阻止您无法完全访问私有值,但如果您有很多“私有”值,它将减少名为
_somePrivate的对象上的成员数量
标签: javascript constructor prototype getter-setter