JavaScript失去了“这个”具有私有/公共属性的对象引用 [英] JavaScript losing "this" object reference with private/public properties

查看:83
本文介绍了JavaScript失去了“这个”具有私有/公共属性的对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下页面时出现以下错误:

I have the following error when running the page below:

this.testpublic不是函数

"this.testpublic is not a function"


test = function() {
        var testprivate = function() {
                this.testpublic();
        }

        this.testpublic = function() {
                console.log('test');
        }

        testprivate();
}
new test();

显然当 testprivate 是调用,this开始指向window而不是对象。

Apparently when testprivate is called, "this" starts pointing to "window" instead of the object.

在同一个对象中,JavaScript不应该保留this上下文吗?

Shouldn't JavaScript preserve "this" context when within the same object?

推荐答案

调用testprivate时需要操作上下文。您可以使用function.call覆盖函数的范围。试试这个:

You need to manipulate the context when calling testprivate. You can use function.call to override the scope of the function. Try this:

test = function() {
        var testprivate = function() {
                this.testpublic();
        }

        this.testpublic = function() {
                console.log('test');
        }

        testprivate.call(this);
}
new test();

这篇关于JavaScript失去了“这个”具有私有/公共属性的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆