我相当肯定这是不可能的,但想看看是否有人对如何使其成为可能有一些巧妙的想法。
我希望以下代码工作:
var x = new foo();
x.a.getThis() === x; // true
换句话说,我想x.a.getThis
参考this
在x
这种情况下。说得通?
为了让它深入一层很简单:
function foo(){}
foo.prototype.getThis = function(){ return this; }
var x = new foo();
x.getThis() === x; // true
有一件事,我希望它可以作为原型工作,而不是通过手动绑定来“作弊” this
:
function foo(){
this.a = {
getThis : (function(){ return this; }).bind(this)
};
}
尽管上面是我想要实现的完美功能示例,但我只是不希望每个实例都有所有额外的功能:)
仅供参考,这里的实际用例是我正在创建类来表示节点中的 Cassandra 对象,并且我希望能够通过引用超级列 --> 列族 --> 列foo.a.b
并foo
在深层功能。