There is a code of this type:
function test() { return { foo: 2, bar: 3, value: this.foo + this.bar } } Why this does not refer to the desired object?
There is a code of this type:
function test() { return { foo: 2, bar: 3, value: this.foo + this.bar } } Why this does not refer to the desired object?
The this.foo + this.bar expression this.foo + this.bar occurs in the context of the test function. You cannot, at the time you create a new object, access its properties.
You can achieve a similar result like this:
function test() { return { foo: 2, bar: 3, get value() { return this.foo + this.bar; } }; } console.log(test().value); In this case, the value of the value property will be calculated dynamically.
An object is not yet created when you use this in an expression and therefore it is not defined. In order to pass an object context, you can use the bind() function.
function test() { return { foo: 2, bar: 3, value: function() { return this.foo + this.bar; } }; } console.log(test().value()); Source: https://ru.stackoverflow.com/questions/851900/
All Articles