我对 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();
错误是: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();
所以,据我所知,在某个时刻之后,“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();
关于javascript - "This"未引用当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12356662/