我正在使用javascript。声明实例变量"this.variable"将一直有效,直到我的函数返回对象为止。返回一个String,Number不会影响它。在返回一个对象的情况下,实例变量不再工作,变成"未定义"。请你帮帮我!(在http://jsfiddle.net/woko/vE4rq/2/在firefox&铬)
function Funct() {
this.varfunc = "this ist a instance";
return false;
}
var f = new Funct();
console.log(f.varfunc);
function FunctReturnobj() {
this.varfunc = "this ist a instance + return an object";
return {};
}
var fr = new FunctReturnobj();
console.log(fr.varfunc)
函数作用域中的this
是DOMWindow
。
对象范围内的this
是对象。
您使用构造函数的方式不对。建设者自己不应该归还任何东西。您可以使用prototype
属性来声明"类"/对象方法,也可以像您已经做的那样在构造函数中设置它们:
function Constructor(value) {
this.variable = value;
}
var obj = new Constructor('test');
obj.variable; // -> Returns 'test';
与您可以声明对象的方法相同:
function Constructor(value) {
this.variable = value;
this.say = function(something) {
return "I say: " + something;
};
}
或者原型方式:
function Constructor(value) {
this.variable = value;
}
Constructor.prototype.say = function(something) {
return "I say: " + something;
};
当然,这是一个普通的、有点糟糕的例子,但你可能明白了:)
new
运算符将创建一个新对象并在其上应用函数-函数范围中的this
指的是该对象。
但是,当函数在没有new的情况下被调用,或者包含返回语句时,它将不会作为"构造函数"执行。this
将指向执行上下文,通常是window
对象。