This question already has answers here:
How do JavaScript closures work?
(86 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
I don't understand why this.name isn't the same as obj.name, basically why in this case this refers to the window object and not the obj object. In the code below, this.name is instantiated after obj.name..
function createNewPerson(name) {
var obj = {};
obj.name = name;
alert(this.name);
return obj;
}
Per MDN:
Inside a function, the value of this depends on how the function is
called. Since the following code is not in strict mode, and because
the value of this is not set by the call, this will default to the
global object , which is window in a browser.
So in your case you have this as the Window object, not the obj. You may get the obj context inside your function via binding it manually, for example:
function createNewPerson(name) {
console.log(this.name); // Hello
console.log(name); // World
}
var obj = {};
obj.name = 'Hello';
var salva = createNewPerson.apply(obj, ['World']);
But what you really need, as I can understand, is a function cunstructor and instantiating an object via new operator:
function createNewPerson(name) {
this.name = name;
}
var salva = new createNewPerson('Salva');
console.log(salva.name); // Salva
Related
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Can someone explain to me why the second function call returns undefined? I see no reason for that. The reference of the object method is stored in a variable, so it should be printed out. Why the result is undefined? The first function call is successful and the only difference is that the second one is stored in a variable.
const module = {
x: 42,
getX: function() {
return this.x;
}
};
//1 - returns 42
console.log(module.getX());
//2 - returns undefined
const unboundGetX = module.getX;
console.log(unboundGetX());
Because unboundGetX function is called by the global window variable, unboundGetX() it's like writing window.unboundGetX() so the this will refer to the global scope which is "window" object so it's also like you wrote return window.x which is logically "undefined".
it will be better to bind your scope to the same object like this :
const module = {
x: 42,
getX: function() {
return this.x;
}
};
console.log(module.getX());
const unboundGetX = module.getX.bind(module); // we bind getX function to module scope instead of the global scope (which is the window variable)
console.log(unboundGetX());
This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 5 years ago.
Let's say there is a Person:
const Person = function(fname, lname) {
this.fname = fname;
this.lname = lname;
};
And I want to extend its functionality with a "name" getter
Object.defineProperty(Person.prototype, 'name', {
get: () => `${this.fname} ${this.lname}`
});
However, this does not work. The this in the getter is not the instance prototype on which it is called:
const p = new Person('Taylor', 'Swift');
p.name // "undefined undefined"
Rather it is the scope of the property definition:
fname = 'Someone';
lname = 'Else';
p.name // "Someone Else"
In the process of writing this question, the answer was obvious. Still posting in case it helps someone else.
Getter properties are indeed bound to their host object.
The issue is that I was using an arrow function for the getter. The arrow function does not have its own this, instead using the this value of the enclosing execution context.
This means the binding done for getter properties has no effect.
For example:
const foo = () => this.document;
foo() // global document object
foo.call({document: 'na'}) // still global document object
const bar = foo.bind({document: 'na'});
bar(); // still global document object
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I am new to JS and like other novice struggling to understand concept of THIS keyword in JS. In below snippet name is changed to value1 which I understand since its c object which is calling log function .
But not able to understand why setName function is not able to change value of name variable?
var c ={
name:"value",
log:function(){
this.name="Value 1";
console.log(this.name); // c object is invoking log function hence this refers to c obj
var setName= function(newName){
this.name=newName;
}
setName('Value 2'); // isn't log function calling setName
console.log(this.name);
}
}
c.log();
Value of this is determined by how function is called.
setName is not having context of c object, it is having the global(window) context. Use Function#bind to specify that context.
var c = {
name: "value",
log: function() {
this.name = "Value 1";
console.log(this.name);
var setName = function(newName) {
this.name = newName;
}.bind(this);
setName('Value 2');
console.log(this.name);
}
};
c.log();
This line:
var setName= function(newName){
this.name=newName;
}
Will not neccessary reference the upper function, since your call to it was direct and the dunction is not a direct member of the upper function, something like: this.setName = function()....
So it will refer to a new context.
To change the upper one you have to make another reference for it not using this, like:
var upperThis = this;
var setName= function(newName){
upperThis.name=newName;
}
The function setName creates a new context, so it creates a new this.
This would do the trick:
var that = this;
var setName= function(newName){
that.name=newName;
}
This question already has answers here:
Constructors in JavaScript objects
(19 answers)
Closed 7 years ago.
I have JavaScript function as object:
function hexMesh(){
var side=25;
console.log('hexMesh');
function drawOver(){
}
}
As you can see it has a function call drawOver.
I try to call it by using a constructor as follows:
window.onload = function() {
hexMeshObj=new hexMesh();
hexMeshObj.drawOver();
}
But it gives me error saying undefined is not a function
Now I know I could declare the function in the prototype of the object but I don't want to do that.
Here it is on JSFiddle.
You can't use JavaScript like that!
Solution: Use Class-like prototypes (please don't treat them as classes, although they provide inheritance)
var x = function(v){ this.test = v; } // This is your constructor
x.prototype.show = function(){ console.log("TEST", this.test); } // This is a prototype with this as a context
var y = new x(true);
y.show(); // Logs TEST true
Edit:
Alternatively (although the prototype way is better as it provides real inheritance the oop way)
var x = function(v){
var context = this;
this.test = v;
this.show = function(){
console.log('test', context.test)
});
Another alternative way is to use bind to bind context if you need it.
This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
Just to carify, I'm not asking the difference of function declaration and function variable.
For example:
var Klass = function() {};
Klass.prototype._fn1 = function fn1() {};
Klass.prototype._fn2 = function fn2() {};
So, my question is what is the purpose of doing this? Why can't just write:
var Klass = function() {};
Klass.prototype._fn1 = function() {}; // <-- note that the function has no name, it just be assigned to the object as a property
Klass.prototype._fn2 = function() {};
Basically this means you are adding the method _fn1() to Klass Constructor.
Klass.prototype._fn1 = function fn1() {};
And this method is available over the object which is made by using Klass() Constructor.
myObj = new Klass();
myObj._fn1() //you can access the method like this