在对象创建期间'this'上下文

1 javascript closures scope object this

我想做这样的事情:

var test = {
    a: 10,
    b: 20,
    c: (this.a+this.b)
};
Run Code Online (Sandbox Code Playgroud)

但它不起作用.如何从test.c中访问test.a?可能吗?

mbr*_*ort 5

在指定对象文字的表达式中引用"this"是不可能的.要么在以下行中执行,要么使用如下构造函数:

function myobj(a,b) {
  this.a = a;
  this.b = b;
  this.c = this.a + this.b;
}

var test = new myobj(10,20);
Run Code Online (Sandbox Code Playgroud)

响应哪种方法更快,使用对象构造函数创建更快.这是一个简单的测试用例比较.在JSBIN上自己运行它.

结果表明,对象创建使用构造VS对象文本几乎是两倍的速度:

0.450s:testObjectLiteral

0.506s:testObjectLiteralWithFunction

0.280s:testConstructor

这里也是内联的测试代码:

// timer function
function time(scope){ 
  time.scope = time.scope || {}; 
  if(time.scope[scope]) {
    var duration = (new Date()).getTime()-time.scope[scope]; 
    time.scope[scope] = null; 
    var results = document.getElementById("results");
    results.innerHTML = results.innerHTML + '<p>'+(duration/1000).toFixed(3)+'s : '+scope+'</p>';
  } else { 
    time.scope[scope] = (new Date()).getTime();
  } 
}  

// object creation function with constructor
function myobj(a,b) {
  this.a = a;
  this.b = b;
  this.c = this.a + this.b;
}

function testConstructor(iterations) {
  var objs = new Array(iterations);
  for(i=0;i<iterations;i++) {
    objs[i] = new myobj(i,i+1);
  }
  return objs;
}

function testObjectLiteralWithFunction(iterations) {
  var objs = new Array(iterations);
  for(i=0;i<iterations;i++) {
    objs[i] = {
      a: i,
      b: i+1,
      c: function() {
        return this.a + this.b;
      }
    };
  }  
  return objs;
}


function testObjectLiteral(iterations) {
  var objs = new Array(iterations);
  for(i=0;i<iterations;i++) {
    var item = {
      a: i,
      b: i+1
    };
    item.c = item.a + item.b;
    objs[i] = item;
  }  
  return objs;
}

var ITERATIONS = 1000000;
time("testObjectLiteral");
testObjectLiteral(ITERATIONS);
time("testObjectLiteral");

time("testObjectLiteralWithFunction");
testObjectLiteralWithFunction(ITERATIONS);
time("testObjectLiteralWithFunction");

time("testConstructor");
testConstructor(ITERATIONS);
time("testConstructor");
Run Code Online (Sandbox Code Playgroud)