如何交叉引用javascript类属性?

时间:2014-06-18 09:53:40

标签: javascript class scope

在一个项目中,我遇到了javascript范围的问题。这是一个基本问题,但由于我对js相对较新,很难看出这段代码存在问题。

我得到的例外是:Uncaught TypeError:无法读取属性' firstProperty'未定义的。

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();

2 个答案:

答案 0 :(得分:0)

这是因为尚未定义_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. 由于函数是对象并且可以具有属性,因此可以将其用作对象构造函数,但现在我要离开主题,所以我会停止
  4. 这将有助于您在将来查找更多相关信息

答案 1 :(得分:0)

如果您想引用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上查看。