【问题标题】:How to crossreference javascript class-properties?如何交叉引用javascript类属性?
【发布时间】:2014-06-18 09:53:39
【问题描述】:

在一个项目中,我遇到了 javascript-scope 的问题。这是一个基本问题,但由于我对 js 比较陌生,所以很难看出这段代码的问题。

我得到的异常是:Uncaught TypeError: Cannot read property 'firstProperty' of undefined。

The jsfiddle

小提琴的代码:

var someClass = function(){
  var _someClass = {
    firstProperty: 'hello world',
    secondProperty: _someClass.firstProperty, // This line is not working like I expected it to work 
  }   

  return _someClass;
}

var someObject = new someClass();

【问题讨论】:

    标签: javascript class scope


    【解决方案1】:

    如果你想引用firstProperty,那么你可以这样使用:

    var someClass = function() {
    
      var _someClass = new (function() {
        this.firstProperty = 'hello world';
        this.secondProperty = this.firstProperty;
      })(); 
    
      return _someClass;
    }
    
    var someObject = new someClass();
    
    console.log(someObject.firstProperty);
    console.log(someObject.secondProperty);
    

    JSFiddle 上查看。

    【讨论】:

    • 我只是好奇,为什么new(function(){})()
    • @Loupax 只是设置this的上下文。
    【解决方案2】:

    这是因为_someClass.firstProperty 尚未定义。要完成这项工作,您应该执行以下操作:

    var someClass = function(){    
        var _someClass = {};
        _someClass.firstProperty = 'hello world';
        _someClass.secondProperty = _someClass.firstProperty;
    
        return _someClass;
    }
    
    // The new here isn't actually necesary, 
    // since the object is created at the first 
    // line of the function. I actually don't 
    // know what happens here
    var someObject = new someClass();
    

    另外,为了避免以后的麻烦,请记住 JS 没有类。 someClass 是:

    1. 一个对象
    2. 一个函数
    3. 由于函数是对象并且可以具有属性,因此您可以将其用作对象构造函数,但现在我跑题了,所以我会停下来

    这将帮助您在以后查找更多相关信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      相关资源
      最近更新 更多