我不太懂JavaScript原型。在下面的示例中,为什么tmp.foo.tt()的输出未定义,以及如何定义它?
function Test(){
this.name = 'test'
}
Test.prototype.foo = {
tt: function(){
console.log(this.name)
}
}
var tmp = new Test();
tmp.foo.tt() //why the output is undefined, and how to change it发布于 2016-05-07 08:31:27
您可以使用getter来解决这个问题,尽管您将失去原型通常提供的一些优势:
function Test(){
this.name = 'test'
}
Object.defineProperty(Test.prototype, 'foo', {
get: function() {
var that = this;
// that is now this
return {
tt: function(){
console.log(that.name);
}
}
},
configurable: true,
enumerable: true
});
var tmp = new Test();
tmp.foo.tt();https://stackoverflow.com/questions/37086106
复制相似问题