JS class without constant reference to “this” for

2019-06-22 12:27发布

问题:

My typical JS class structure looks like this:

MyClass = function(args)
{
   this.myProp1 = undefined;
   this.myProp2 = args[0];
   //...more member data 

   this.foo = function()
   {
       return this.myProp1 + this.myProp2; //<- the problem.
   }
   //...more member functions
}

//if MyClass extends a superclass, add the following...
MyClass.prototype = Object.create(MySuperClass.prototype);
MyClass.prototype.constructor = MyClass;

...My ongoing annoyance with JS is that I seem to have to use this continuously in member functions in order to access the properties of the very same object to which those functions belong. In several other languages e.g. C# & Java, this may be safely omitted when member functions are working with member data in the same class / instance. (I realise that JS is structured fundamentally differently due to it being designed as a prototypal rather than a hierarchical inheritance language.)

To put the question another way: Is there any way to make the unspecified scope NOT point to window, but rather to the current, local value of this?

P.S. I am guessing this is a language limitation, but thought I'd check again anyway.

回答1:

There is a keyword which partially does what you want: with but it is highly not recommended to use it, because ambiguous in some cases.

If you access a non existing member it will fallback to the window object. So what you could do is declare all the properties you are going to use later and then declare a with statement.

If I had the choice you have, I'd probably change my mind about skipping this or if you can, use another language.



回答2:

I am not sure is it Language limitation or something else, but the pattern you have used for Class and member function creations, will not help to achive that you want to.

Why do not you try Module Pattern like this ?

CalcModule = (function(){
                var add = function(a, b) {
                    return a + b;
                };

                var sub = function(a, b) {
                    return a - b;
                };

                var _privateCalculation = function(){
                };

                return {
                     "add" : add,
                     "sub" : sub
                };

});

Here you get a control to mimic private members by not having them in return object. I hope this helps.

Update : I am not sure about extension of Module pattern classes.

Update : Added var for function declarations



回答3:

In several other languages e.g. C# & Java, this may be safely omitted when member functions are working with member data in the same class / instance. (I realise that JS is structured fundamentally differently due to it being designed as a prototypal rather than a hierarchical inheritance language.)

It's not about the inheritance chain, which is rather static in js as well. It's about JS being a dynamic language, with the global scope being able to add new variables at will, and objects being amendable with arbitrary properties.

So it's just not really possible to make an identifier dynamically resolve to either a local variable or an object property, and we want to distinguish explicitly between them every time by using property accessors for property access.

Is there any way to make the unspecified scope NOT point to window, but rather to the current, local value of this?

The "unspecified scope" is the local scope, which is statically determined and optimized. To make it point to an object (and fall back to variables if the property is not found), you can use the with statement. However, due to this ambiguity it's not only slow, but also considered bad practise - the lookup (of variables) can be influenced by non-local code (that interacts with the instances) which breaks encapsulation and is a maintainability issue.

My typical JS class structure …

Of course you could also change that, and use local variables that are accessed via closure as members instead (see also Javascript: Do I need to put this.var for every variable in an object?). This solves the problems with this, but is also a bit slower (though probably still faster than with).



回答4:

It's probably best to avoid using a with statement because the presence of a with statement disables optimization. Also, a with statement cannot be used in strict mode. See ECMA 262 §12.10.1: "Strict mode code may not include a WithStatement. The occurrence of a WithStatement in such a context is treated as a SyntaxError."

One option is to use a syntax extension that expands to a property access. For instance, in CoffeeScript 0.3.2, @property was added as shorthand for this.property.

If you don't want to use CoffeeScript, you can create your own macro with sweet.js. Here is an example of a macro that adds the @property shorthand feature:

macro @ {
    case { _ $x:ident } => { return #{ this.$x }; }
    case { _ $x } => { return #{ this[$x] }; }
}

function Person(name) {
    @name = name;
}

var person = new Person("Johnny Appleseed");
alert(person.name);

The sweet.js compiler, sjs, generates:

function Person$630(name$632) {
    this.name = name$632;
}
var person$631 = new Person$630('Johnny Appleseed');
alert(person$631.name);


回答5:

Adding my own answer here for posterity, because at some stage, if I'm stuck between being forced to (1) prepend this and (2) using the terrifying with, it might be useful to have a (3)rd solution.

Let's assume we do not access any member data directly; instead we have getter and setter methods for each data property.

In this case, it's possible to use the private concept as discussed by Doug Crockford:

MyClass = function()
{
   var prop = undefined;
   this.getProp() {return prop;}
   this.setProp(value) {prop = value;}

   //now in standard, non-getter and -setter methods, we can do...
   this.foo = function()
   {
       return prop + prop; //<- no problem: no more 'this'
   }
}

And a (4)th solution, less safe but also less verbose:

MyClass = function()
{
   var prop = this.prop = undefined; //this.prop for read only! (unsafe)
   this.setProp(value) {prop = this.prop = value;}

   //now in standard, non-getter and -setter methods, we can do...
   this.foo = function()
   {
       return prop + prop; //<- no problem: no more 'this'
   }
}

In (4), we need only setters, reducing verbosity greatly.

With few methods containing a lot of logic, this works well. With many smaller methods, its sheer size (all those accessor methods) end up outweighing the benefit of avoiding this every time we access a local member. Still -- it does lead to cleaner in-function logic.