【问题标题】:Javascript: Function - Return an Object will invalid this.variableJavascript:函数 - 返回一个对象将使 this.variable 无效
【发布时间】:2012-03-30 07:45:52
【问题描述】:

我正在使用 JavaScript。声明一个实例变量“this.variable”将一直有效,直到我的函数返回一个对象。返回一个字符串,数字不影响它。在返回对象的情况下,实例变量不再起作用并变为“未定义”。请你帮帮我! (在 http://jsfiddle.net/woko/vE4rq/2/ 寻找在最新版本的 firefox 和 chrome 下测试的示例)

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)

【问题讨论】:

    标签: javascript function this instance-variables


    【解决方案1】:

    this在函数范围内是DOMWindow

    this在对象范围内对象。

    【讨论】:

      【解决方案2】:

      您以错误的方式使用构造函数。构造函数不应该自己返回任何东西。您可以使用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;
      };
      

      当然,这是一个通用且有点糟糕的例子,但你可能明白了:)

      【讨论】:

      • 感谢您的时间和示例!
      【解决方案3】:

      new 运算符将创建一个新对象并在其上应用函数 - 函数范围内的 this 指的是该对象。

      但是当函数在没有 new 的情况下被调用,或者包含 return 语句时,它不会作为“构造函数”执行。 this 将指向执行上下文,通常是 window 对象。

      【讨论】:

      • 非常感谢,这是我的解决方案!使用 return 语句调用函数将不会作为“构造函数”执行
      猜你喜欢
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2014-05-22
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      相关资源
      最近更新 更多