1

I have this piece of Javascript code:

$scope.rectifyForm =
{
    visible: false,
    rateErrorMessage: "",
    rectifyErrorMessage: "",
    isValid: function () {
        return this.rateErrorMessage.length === 0 && this.rectifyErrorMessage.length === 0;
    }
};

In the isValid method I want to check of both variables are set. This piece of code works because I've used the this keyword. However, If I omit this, I get an error that these variables are undefined.

Could somebody explain why this is? Why do I need to use this?

2 Answers 2

4

rateErrorMessage is not a variable in the scope of the function being called; it is a property of an object (so you have to specify theObject.rateErrorMessage). Since that object is the context in which the function is called, it is available via this.

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

3 Comments

But the function and both properties are part of the same object, so why doesn't javascript recognize those properties?
It does, but properties and variables are very different things.
@Martijn This feature is simply not provided by the language.
0

When a function is called as a method of an object, its 'this' is set to the object the method is called on.

isValid is a function defined inside the scope of rectifyForm which also includes the variable rateErrorMessage. But the function definition has no direct link to rateErrorMessage. hence, to access the variable inside the function, one need to use 'this' which actually points to the scope of rectify form. if you don't use 'this' then the variable will be undefined in the function.

your code can be written in the following way as well- function isValid() { return this.rateErrorMessage.length === 0 && this.rectifyErrorMessage.length === 0; }

and then, $scope.rectifyForm.isValid = isValid;

For a detailed information on 'this' keyword, you can refer to this in javascript

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.