原型 javascript 中的全局实例
我正在探索一种模式,您可以保存对当前实例的全局引用,以便在 this
关键字脱离上下文的匿名函数中简单使用。考虑一下:
var instance;
var a = function(id) {
instance = this;
this.id = id;
};
a.prototype.get = function() {
return (function() {
return instance.id;
})();
};
var x = new a('x');
var y = new a('y');
console.log(x.get());
console.log(y.get());
这显然行不通,因为实例是在构造函数中定义的,每次调用 .get()
时,instance
将引用最后构造的对象。所以它两次都会产生“y”。
但是,我正在寻找一种在不使用 this
关键字的情况下获取原型方法内的实例的方法,以使代码更具可读性。单例在这里不是一个选项,我需要原型继承。
I am exploring a pattern where you can save a global reference to the current instance for simple use in anonymous functions where the this
keyword is out of context. Consider this:
var instance;
var a = function(id) {
instance = this;
this.id = id;
};
a.prototype.get = function() {
return (function() {
return instance.id;
})();
};
var x = new a('x');
var y = new a('y');
console.log(x.get());
console.log(y.get());
This obviously won't work since instance is defined in the constructor, to each time .get()
is called, instance
will reference the last constructed object. So it yields 'y' both times.
However, I'm looking for a way to grab the instance inside a prototype method without using the this
keyword, to make the code more readable. Singletons is not an option here, I need the prototypal inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:由于您要避免存储“本地实例”,因此有一些方法,例如:
使用
调用
或apply
更改调用函数的this
值:使用参数:
新的 ECMAScript 第五版引入
bind
方法,对于保留this
值和可选绑定参数非常有用,您可以找到兼容的实现此处:Edit: Since you're avoiding to store "local instances", there are some approaches, for example:
Using
call
orapply
to change thethis
value of the invoked function:Using an argument:
The new ECMAScript 5th Edition introduced the
bind
method, which is extremely useful to persist thethis
value and optional bound arguments, you can find a compatible implementation here: