首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >javascript原型对象这个值

javascript原型对象这个值
EN

Stack Overflow用户
提问于 2016-05-07 08:07:04
回答 1查看 65关注 0票数 0

我不太懂JavaScript原型。在下面的示例中,为什么tmp.foo.tt()的输出未定义,以及如何定义它?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-07 08:31:27

您可以使用getter来解决这个问题,尽管您将失去原型通常提供的一些优势:

代码语言:javascript
复制
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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37086106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档