ES 6 Class : Access "this" in another scope [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I have a ES6 Class in NodeJS 4.
In the constructor, I want to modify the prototype of an object, so that it now use this class instance to perform an operation.
But, of course, in the prototype scope, this doesn't refer to the instance of the class i'm creating.
class Generic {
constructor() {
this.myClass = util._extend({}, aClass); //shallow copy
this.myClass.prototype.run = function(fn) {
var str = this.toString;
//in the next line, _this_ should refer to the Generic instance.
this.run(str, fn);
};
}
do() {
return this.myClass;
}
run(str, fn) {
...
}
How can I refer the Generic class instance being created on the myClass prototype scope ?

Some options:
bind:
this.myClass.prototype.run = (function(fn) {
// `this` is the Generic instance.
}).bind(this);
that:
var that = this;
this.myClass.prototype.run = function(fn) {
// `that` is the Generic instance.
};
Arrow functions:
this.myClass.prototype.run = fn => {
// `this` is the Generic instance.
};

Related

Javascript "this" not set in function that was passed around [duplicate]

This question already has answers here:
"This" within es6 class method [duplicate]
(1 answer)
How to access the correct `this` inside a callback
(13 answers)
Closed last month.
I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?
I have an oversimplified example:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) { this.printIt(x); };
}
}
(new myclass).getFunc()("test");
TypeError: Cannot read properties of undefined (reading 'printIt')
And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
let self = this;
return function(x) { self.printIt(x); };
}
}
(new myclass).getFunc()("test");
class myclass {
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) {
this.printIt(x);
}.bind(this);
}
}
(new myclass).getFunc()("test");

this is window inside the function of a class [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
I have some code here.
I am aware that this reference wont be carried in anonymous functions.
But here, even when using a function of an object, the this inside that is window.
var MyClass = function (div) {
this.array = [];
};
MyClass.prototype = {
addToArray: function (elem) {
this.array.push(elem);
},
processAndAdd: function(elemArray){
elemArray.forEach(this.addToArray);
}
}
var myObj = new MyClass();
myObj.processAndAdd([1, 2, 3]);
console.log('test');
Error: Line: this.array.push(elem);
push of undefined.
On inspection, the this here is window Object
I want to know why this is window here, and how to restructure my code to properly handle this.
The reference to this object is no more MyClass constructor after you pass the callback function body as callback to forEach. Bind the function body with the current this context and your code should work.
var MyClass = function (div) {
this.array = [];
};
MyClass.prototype = {
addToArray: function (elem) {
this.array.push(elem);
},
processAndAdd: function(elemArray){
elemArray.forEach(this.addToArray.bind(this));
}
}
var myObj = new MyClass();
myObj.processAndAdd([1, 2, 3]);
console.log('test');

JavaScript - this inside of timeout with arrow functions [duplicate]

This question already has answers here:
What does "this" refer to in arrow functions in ES6?
(10 answers)
Closed 6 years ago.
Why isn't this inside of the setTimeout equal to the object that invoked the render function when using arrow functions?
class X {
constructor(config) {
this.data = config.data;
this.render_ = config.render;
}
render() {
this.render_(this.data);
}
}
var x = new X({
data: [1, 2, 3],
render: (data) => {
setTimeout(() => {
console.log(this);
}, 200);
}
});
x.render();
Read the part of the arrow function documentation that says "Arrow functions used as methods"
in summary: arrow functions just simply do not bind this or their own version of this, but rather references the global Window object.
Because arrow functions are lexically bound. That means they take on the value of "this" at the time of declaration. They are not affected by other means of modifying the this value, including being called as a method or functions like bind, apply and call.
function F() {
this.type = 'F';
this.logTypeExpression = function() {
console.log(this.type);
};
this.logTypeArrow = () => {
console.log(this.type);
};
}
function G() {
this.type = 'G';
}
var f = new F();
var g = new G();
f.logTypeExpression(); // F
f.logTypeArrow(); // F
// Now lets give these functions to G
g.logTypeExpression = f.logTypeExpression;
g.logTypeArrow = f.logTypeArrow;
g.logTypeExpression(); // G
g.logTypeArrow(); // F(!) (That's because `this` was assigned by the arrow function)
At the time that the arrow function is created, this isn't bound to any object, so it still refers to window. Maybe you want to try console.log(x); if you want to refer to that specific instance?
The code below only holds a reference to the function you created using an object literal syntax.
this.render_ = config.render;
Using bind(this) will tell the function to use the parameter object as the this reference when calling the function in the instance of your X object.
class X {
constructor(config) {
this.data = config.data;
this.render_ = config.render.bind(this);
}
render() {
this.render_(this.data);
}
}
Also, it does not matter if it's an arrow function or a regular function expression in your code snippet.

what is the difference between a method within JS function and to it's prototype? [duplicate]

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 6 years ago.
As output of both the below JS class is same, then what is special here with prototype?
One of the feature of prototype is get rid of duplicate code, in what case this is possible with prototype?
1.
function Person(name) {
this.name = name;
this.sayName = function () {
console.log(this.name);
};
}
var person1 = new Person("Nicholas");
person1.sayName();
2.
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function () {
console.log(this.name);
};
var person1 = new Person("Nicholas");
person1.sayName();
If you assign a property by using prototype then those properties will be shared through out all the instances of the class/constructor which has the particular prototype. But assigning a property using this inside of the constructor will be instance-specific. They cannot be shared with other instances. Each instances will have their own value in it.

What does 'return this' do when augmenting types? [duplicate]

This question already has answers here:
What does "return this" do within a javascript function?
(4 answers)
Closed 7 years ago.
Crockford's book JavaScript the Good Parts talks about a function for augmenting basic types. His function looks like this:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
I don't understand how / why the 'this' variable is used here. I've only used 'this' when calling that function with 'new', but this function is instead called like this:
Number.method('integer', function () {
return Math[this < 0 ? 'ceil' : 'floor'](this)
});
this refers to the Object which the function was referenced though when invoked.
var obj = {fn: function() {return this;}};
obj.fn(); // obj
var fn = obj.fn;
fn(); // window or null or error
fn.call(obj); // obj
fn.apply(obj); // obj
method is on Function.prototype, this means all Function instances inherit method and this inside method is expected to refer to the function instance which you're invoking it though, i.e.
Function.prototype.getThis = function () {return this;};
function hello() {}
hello.getThis(); // hello
// and consequently
hello.getThis().getThis().getThis().getThis().getThis(); // hello
Constructors are Functions too. Therefore all constructors inherit the method. The method example here hence means "Add a property name to the prototype inherited by instances of this (the constructor) and set the value of that property to func, then return the constructor so you can chain it"
function Foo() {}
Foo.method('bar', 'baz').method('fizz', 'buzz'); // Foo
var foo = new Foo();
foo.bar; // "baz", inherited from Foo.prototype
foo.fizz; // "buzz", inherited from Foo.prototype
this refers to its execution context. More precisely, it's used inside a function, and refers to the object that invoked it.

Categories

Resources