简体   繁体   中英

Any way to avoid all the “this” in Javascript objects?

When defining a JS object with a constructor function, is there any way to avoid having to use "this" with every single object property? It seems very ugly. Eg

function Thingy(abc) {
  this.var1 = abc;
  this.var2 = this.var1 + " hello ";
  // etc
}

var myObj = new Thingy();

It seems that I should be able to use "var var2" and then leave out the "this" and just refer to "var2", but am I missing something?

You can use any object you like and simply return it at the end eg:

function Thingy(abc) {
  var thingy = {};
  thingy.var1 = abc;
  thingy.var2 = thingy.var1 + " hello ";
  return thingy;
}

Or

function Thingy(abc) {
  var thingy = {
    var1: abc,
    var2: abc + " hello "
  };
  return thingy;
}

Or

function Thingy(abc) {
  return {
    var1: abc,
    var2: abc + " hello "
  };
}

Or

function Thingy(abc) {
  var var1 = abc,
      var2 = var1;
  var2 += " hello ";
  return {
    var1: var1,
    var2: var2
  };
}

Well, I'm afraid that you're running into how the language is designed.

But there is a sense in which you can use the plain var statements from the constructor. Any functions created in there have access to the closure that includes these properties:

function Thingy(abc) {
    var var1 = abc;
    this.func1 = function(str) {return var1 + ", hello";};
}

var thing1 = new Thingy("Dan");
thing1.func1();  // => "Dan, hello"

Note this is how you can encapsulate entirely private variables in an object, so it's often a useful technique.

Nope, there's no way to avoid it. You need to use this to assign variables to an object.

try

function Thingy(abc) {
  with(this)
  {
    var1 = abc;
    var2 = this.var1 + " hello ";
  // etc
  }
}

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM