Javascript 当原型包含对象时是否接受“this”值?
我有一门课是这样的:Javascript 当原型包含对象时是否接受“this”值?,javascript,object,prototype,Javascript,Object,Prototype,我有一门课是这样的: function Foo() { this._current = -1; } Foo.prototype.history = {}; Foo.prototype.history.back = function () { if (this._current === undefined) { return alert("this._current is undefined"); } --this._current; // `this`
function Foo() {
this._current = -1;
}
Foo.prototype.history = {};
Foo.prototype.history.back = function () {
if (this._current === undefined) {
return alert("this._current is undefined");
}
--this._current; // `this` is the history object
};
var f = new Foo();
f.history.back = f.history.back.bind(f);
如何在back
方法中访问Foo
实例
我看到的解决方案是这样做:
function Foo() {
this._current = -1;
}
Foo.prototype.history = {};
Foo.prototype.history.back = function () {
if (this._current === undefined) {
return alert("this._current is undefined");
}
--this._current; // `this` is the history object
};
var f = new Foo();
f.history.back = f.history.back.bind(f);
有更好的解决办法吗?对每个Foo
实例都这样做对我来说不太好
以下是一个例子:
函数Foo(){
这个。_电流=-1;
}
Foo.prototype.history={};
Foo.prototype.history.back=函数(){
如果(此._当前===未定义){
返回警报(“此。_当前未定义”);
}
--this._current;//`this`是历史对象
};
var f=新的Foo();
f、 历史。返回()代码>代码中的基本问题是,在Foo
的所有实例之间,您只有一个history
对象共享。您必须为每个实例创建一个历史记录
。解决办法是:
函数历史记录(foo){
这个;
}
fooshistory.prototype.back=函数(){
如果(此.\u foo.\u当前===未定义){
返回警报(“此._foo._当前未定义”);
}
这个._foo._current--;
};
函数Foo(){
这个。_电流=-1;
this.history=新的FooHistory(this);
}
var f=新的Foo();
f、 历史。返回()代码>代码中的基本问题是,在Foo
的所有实例之间,您只有一个history
对象共享。您必须为每个实例创建一个历史记录
。解决办法是:
函数历史记录(foo){
这个;
}
fooshistory.prototype.back=函数(){
如果(此.\u foo.\u当前===未定义){
返回警报(“此._foo._当前未定义”);
}
这个._foo._current--;
};
函数Foo(){
这个。_电流=-1;
this.history=新的FooHistory(this);
}
var f=新的Foo();
f、 历史。返回()
您的.bind()
解决方案不会真正起作用-每个Foo
实例共享相同的历史
对象。可能是愚蠢的问题。。但是为什么history
不是实例的属性而不是原型?可能重复的或您的.bind()
解决方案不会真正起作用-每个Foo
实例共享相同的history
对象。可能是愚蠢的问题。。但是为什么history
不是实例的属性,而不是原型的属性呢