使用特权Getter/Setter函数的JavaScript原型函数?
问题三部分:使用特权Getter/Setter函数的JavaScript原型函数?,javascript,constructor,prototype,getter-setter,Javascript,Constructor,Prototype,Getter Setter,问题三部分: 添加第二层抽象,并使用原型getter/setter函数调用特权构造函数getter/setter函数有何价值?请参见下面的ns.Wheel.prototype.getWeight2()和ns.Wheel.prototype.setWeight2() 调用swiss.getWeight()调用构造函数中的this.getWeight()方法。是否可以将原型链向上移动一级以调用ns.Wheel.prototype.getWeight() 将原型getter/setter函数“隐藏”在
ns.Wheel.prototype.getWeight2()
和ns.Wheel.prototype.setWeight2()
this.getWeight()
方法。是否可以将原型链向上移动一级以调用ns.Wheel.prototype.getWeight()
ns.Wheel.prototype.getWeight()
隐藏在构造函数中的this.getWeight()
方法后面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.
call
或apply
:ns.Wheel.prototype.setWeight.call(this,1000)
(其中第一个参数为被调用的函数设置this
值,其他参数是实际的函数参数)getWeight2
调用this.getWeight()
时,该函数解析为实例级函数,无需在原型链中查找原型方法
我能看到的唯一的价值可能是,如果您有条件地使用实例方法来隐藏某个原型方法,并且在其他情况下让原型方法显示出来。然而,如果您希望原型方法能够访问构造函数作用域变量,那么您就运气不佳,如第2点所述。例如:
function Egg(color) {
if(color == "invisible") {
this.examine = function() { return "You can't see the egg at all! }
}
}
Egg.prototype.examine = function() { return "The egg is painted " + color; }
这不是一个很好的例子(它可以更好地处理像数字这样的简单值,而不是函数),但它是我能想到的唯一一个原型阴影“有用”的例子call
或apply
:ns.Wheel.prototype.setWeight.call(this,1000)
(其中第一个参数为被调用的函数设置this
值,其他参数是实际的函数参数)getWeight2
调用this.getWeight()
时,该函数解析为实例级函数,无需在原型链中查找原型方法
我能看到的唯一的价值可能是,如果您有条件地使用实例方法来隐藏某个原型方法,并且在其他情况下让原型方法显示出来。然而,如果您希望原型方法能够访问构造函数作用域变量,那么您就运气不佳,如第2点所述。例如:
function Egg(color) {
if(color == "invisible") {
this.examine = function() { return "You can't see the egg at all! }
}
}
Egg.prototype.examine = function() { return "The egg is painted " + color; }
这不是一个很好的例子(它可以更好地处理像数字这样的简单值,而不是函数),但它是我能想到的唯一一个原型阴影“有用”的例子