You didn't state if you can use es6 or not. Basically it's a problem of scope. With es6 and babel you can do something like
ES6 Method
var MyObj = function(x) {
this.x = x;
this.y = 5;
};
MyObj.prototype.example = function() {
// I want to return a new object which has access to this.x and this.y
// For example:
return {
addTwo: () => {
// How can I access this.x from the MyObj instance?
return 2 + this.x
}
}
};
In this way this
won't change as arrow functions are having this
context inherited from outer scope.
For the reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Which is basically transpiled to something like this (You are not using classes so I assume you are not using es6)
Old way method
var MyObj = function(x) {
this.x = x;
this.y = 5;
};
MyObj.prototype.example = function() {
// I want to return a new object which has access to this.x and this.y
var that = this
// For example:
return {
addTwo: function(){
// How can I access this.x from the MyObj instance?
return 2 + that.x
}
}
};
which will just "store" this
variable to other variable for later usage (that's what similarly babel does under the cover).
.bind() method
If you wanna 3rd answer you can bind this
context to a called function as this
var MyObj = function(x) {
this.x = x;
this.y = 5;
};
MyObj.prototype.example = function() {
// I want to return a new object which has access to this.x and this.y
var addTwo = function() {
return 2 + this.x
}
// For example:
return {
addTwo: addTwo.bind(this)
}
};
which will "transfer" this
to that function.
For the reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind