javascript - "This"未引用当前对象

标签 javascript this

我对 JS 中的 OOP 有点陌生。我想知道为什么在创建子对象时,在第二级子对象之后 this 不再引用主对象。

function Clase()
{
    this.__construct = function()
    {
    this.paginator();            
    alert('__construct finished');
    };                

    this.paginator = function()
    {

        this.paginator.title = function()
        {
            this.paginator.title.set_offsets  = function()
            {
                alert('paginator.title.set_offsets executed!');

            };
        };

        this.paginator.title(); //instantiating

        alert('subobject paginator created');            
     };

    this.__construct();
}

var instancia = new Clase();

instancia.paginator.title.set_offsets();

http://jsfiddle.net/WYWwE/

错误是:this.paginator未定义。

现在,如果我使用闭包,它就可以完美地工作:

function Clase()
{
    self = this;

    this.__construct = function()
    {
        this.paginator();            
        alert('__construct finished');
    };                

    this.paginator = function()
    {

        self.paginator.title = function()
        {
            self.paginator.title.set_offsets  = function()
            {
                alert('instancia.paginator.title.set_offsets() executed');

            };
     };
     self.paginator.title();

     alert('this.paginator created');
};

this.__construct();
}

var instancia = new Clase();

instancia.paginator.title.set_offsets();

http://jsfiddle.net/esjHu/

所以,据我所知,在某个时刻之后,“this”不再指代“Clase”类,而是指代其他东西。如果是这样,以这种方式使用闭包是一个好习惯吗?

以 self = this; 开始类(class)是否也正确?从那时起只使用“ self ”?例如:http://jsfiddle.net/byGRX/

最佳答案

当您嵌套函数时,您会丢失对“原始”this的引用。要补救,请执行以下操作:

function Clase() {
    var that = this;


    this.paginator = {

        title: {

            set_offsets: function() {
                alert('paginator.title.set_offsets executed!');

            }
        }
    };
};

var foo = new Clase();

foo.paginator.title.set_offsets();​

http://jsfiddle.net/vd5YK/

关于javascript - "This"未引用当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12356662/

相关文章:

javascript - 使用 Greasemonkey 在现有元素之前插入文本节点时出现问题

javascript - 带有 html 工具提示的 Google LineChart <undefined> HTML 标签

javascript - 使用 $(this) 查找表单提交按钮

JavaScript:为什么要获取最后插入的值?

c++ - 清理后删除

javascript - 将iframe内html文件的元素添加到原始文件的DOM树中

javascript - Jquery 选择选项不适用于 switch 和 case

javascript - 普通JS : How to get index of parent element with a certain class?

javascript - 当调用设置为静态方法的变量时,这是未定义的

C++将指向当前对象的指针传递给函数