0

Let's say that I am defining following class to be used in my AngularJs code:

app.factory("exampleClass", function () {
    // constructor
    function exampleClass(val) {
        this.prop1 = val;
        this.result = "";
    }

    // methods
    exampleClass.prototype = {
        doSomething: function (userVal) {
            this.result = this.prop1 + userVal; // any way to avoid this?
            console.log(this.result);
        }
    };

    // return class
    return (exampleClass);
});

// .. later in code
new exampleClass("another").doSomething("321");
console.log(scope.example.prop1);

Is there any way to evade referencing class fields (prop1 and result) with this. in doSomething method, while still being able to reference them from outside of class directly? Obviously I am trying to emulate something like public type fieldName in other modern languages - when this. is not present first look in instance variables?

1 Answer 1

1

Unfortunately no. JavaScript (in the current versions supported by browsers at least) does not support automatic property access from methods.

It is theoretically possible to get the syntax you want with trickery involving with() or local variables and Object.defineProperty, but it will end up making the rest of your code much uglier.

For a more feasible way to get better syntax for JavaScript there's multiple languages out there that compile into JavaScript. One example if CoffeeScript which supports property access with a Ruby-esque @foo syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.