所以我有这两个例子,来自javascript.info:
例1:
var animal = {
eat: function() {
alert( "I'm full" )
this.full = true
}
}
var rabbit = {
jump: function() { /* something */ }
}
rabbit.__proto__ = animal
rabbit.eat()
Run Code Online (Sandbox Code Playgroud)
例2:
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)
从示例2开始:当代码到达时 …
在JavaScript(ES5 +)中,我试图实现以下场景:
.size,可以通过直接属性读取从外部读取,但不能从外部设置..size必须从原型上的某些方法维护/更新该属性(并且应保留在原型上).obj.size = 3;不允许直接设置,就可以在侧门进入酒店.我知道我可以使用在构造函数中声明的私有变量并设置一个getter来读取它,但是我必须移动需要从原型中维护该变量的方法并在构造函数中声明它们(所以他们可以访问包含变量的闭包.对于这种特殊情况,我宁愿不从原型中取出我的方法,所以我正在寻找其他选项可能是什么.
还有什么其他想法(即使有一些妥协)?