String.prototype.foo = {};
String.prototype.foo.bar = function() {
//How can you reference the "grandparent" string?
console.log(this.parent.parent); //obviously, doesn't exist
}
就像这样,"Hello, Nurse!".foo.bar()
将会记录"Hello, Nurse!"。
如果对foo有控制权,是否会有所不同?
编辑:在这里,foo被定义了。
编辑2:好吧,用this.parent.parent
代替this.this.this
。当然parent不存在,但希望现在语义不会成为问题。
编辑3:没有具体的情况。提供的细节基本上是我拥有的全部信息:有一个名为foo的对象,是原型的一部分。foo.bar
是foo
的一个方法,应该访问它的祖父级。就这些,没有其他信息。
编辑4:已解决。根据提供的答案(以及来自Douglas Crockford的一些二手帮助):
String.prototype.foo = function() {
var that = this;
return {
bar : function() {
console.log(that.valueOf());
}
}
}
//Called:
"Hello, Nurse!".foo().bar();
this
仍然是自身,而不是父级。 - Lightness Races in Orbit