当原型包含对象时访问“this"值? [英] Accesing `this` value when the prototype contains an object?

查看:35
本文介绍了当原型包含对象时访问“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
 };

如何访问 back 方法中的 Foo 实例?

How can I access the Foo instance in the back method?

我看到的解决方案是做这样的事情:

I solution I see is to do something like this:

var f = new Foo();
f.history.back = f.history.back.bind(f);

更好的解决方案吗?对每个 Foo 实例都这样做对我来说并不好.

Is there a better solution? Doing that for every Foo instance does not sound good for me.

这是一个例子:

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();

我知道应该是这样,但是解决此类问题的正确方法是什么?

I know it's supposed to be so, but what's the correct way to solve this type of problem?

推荐答案

你的代码的根本问题是你只有一个 history 对象在 Foo.您必须为每个实例设置一个 history.一个解决方案是这样的:

The fundamental problem in your code is that you have only one history object shared between all instances of Foo. You must make it one history per instance. A solution would be this:

function FooHistory(foo){
	this._foo = foo;
}
FooHistory.prototype.back = function() {
  if (this._foo._current === undefined) {
    return alert("this._foo._current is undefined");
  }
  this._foo._current--; 
};

function Foo() {
	this._current = -1;
	this.history = new FooHistory(this);
}
var f = new Foo();
f.history.back();

(您可能希望在 FooHistory 实例中使用 _current 而不是 Foo 实例,我尝试更改尽可能少的代码)

(you probably want to have _current in the FooHistory instance instead of the Foo instance, I tried to change as little code as possible)

请注意,根据更大的视图,其他解决方案也是可能的.如果您没有任何状态要存储在历史对象中,那么您还可以让 Foo.prototype.history() 返回一个对象,该对象的属性链接回 Foo 实例.然后你会调用 f.history().back().

Note that other solutions are possible, depending on the larger view. If you don't have any state to store in the history object then you could also have Foo.prototype.history() return an object with a property linking back to the Foo instance. Then you would call f.history().back().

这篇关于当原型包含对象时访问“this"值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆