How is 'this' working in this context? [duplicate] - javascript

This question already has answers here:
Javascript "this" pointer within nested function
(9 answers)
Closed 5 years ago.
I have a question about how the keyword 'this' works in the following context. Here´s a tutorial with the phaser framework and the code looks like the following(I simply merged it together for you):
var game = new Phaser.Game(400, 490);
game.state.add('main', mainState);
game.state.start('main');
var mainState = {
preload: function() {},
create: function() {
this.bird = game.add.sprite(100, 245, 'bird');
},
update: function() {}
};
In the create function there is a 'this'. I think I understand what this does, but this example proved me wrong. The this keyword - in this context- points to mainState, right(just some information: the create function starts as soon as mainState is called to start the 3rd line)?
I can access the bird outside the mainState object (via mainstate.bird), but why isn't it possible then to define a prototype function like the following outside the game object?
mainState.prototype.myFunction() {}
I´ll get an error calling this and I can't explain.

The mainState is an object literal. 'prototype' is a property of function object in javascript used for prototype inheritance.
Javascript Prototype

One thing that always help me remember what the this will be is to look out for who is calling the function, check this snippet
var sayHi = function() { console.log(this.name) }
var yoda = { name: "Yoda", sayHi: sayHi }
var darthVader = { name: "Anakin Skywalker", sayHi: sayHi }
// the `this` here will be the yoda object
yoda.sayHi()
// the `this` here will be the darthVader object
darthVader.sayHi()
window.name = "Global name"
// here, since nothing was specified, the object is the global object, or the window on browsers, this the same as "window.sayHi()"
sayHi()

Related

Using the constructor method in JS [duplicate]

This question already has answers here:
Why is it necessary to set the prototype constructor?
(14 answers)
Defining a Javascript prototype
(5 answers)
What is the `constructor` property really used for? [duplicate]
(2 answers)
Closed 9 months ago.
I'm learning classes in JS and I'm almost losing my mind with something that seems to be quite simple in OOP.
CONTEXT: I learned that creating a function with methods inserted directly into it will create an unnecessary accumulation of memory, because every time the class is instantiated each instance would have its own method occupying a different space in memory. To solve this we could access the prototype property of the function and put the methods directly there; however automatically every function has a prototype with a constructor property that points directly to the function and if I create a prototype from the outside I will overwrite the function's prototype and leave it without the constructor property, so I added this property directly to the prototype created manually.
QUESTION: my question is what is the difference of the function without the constructor property, as apparently the two codes worked similarly?
Code source: The Objective Programmer.
CODE WITH CONSTRUCTOR:
function Person (name){
this.name = name;
}
Person.prototype = {
constructor: Person,
sayName: function (){
console.log(this.name);
},
toString: function(){
return "[Person" + this.name + "]";
}
}
CODE WITHOUT CONSTRUCTOR:
function Person2 (name){
this.name = name;
}
Person2.prototype = {
sayName: function (){
console.log(this.name);
},
toString: function(){
return "[Person" + this.name + "]";
}
}
A seen on this section of the MDN docs on this topic, there won't be a difference here, as you're not technically changing the constructor on either object.
Where this would matter, however, is if you changed the constructor of the function. Take the following code snippet from the aforementioned MDN page:
function Parent() { /* ... */ }
Parent.prototype.parentMethod = function parentMethod() {}
function Child() {
Parent.call(this) // Make sure everything is initialized properly
}
Child.prototype = Object.create(Parent.prototype) // re-define child prototype to Parent prototype
Child.prototype.constructor = Child // return original constructor to Child
The important part of this figure is that at the end, you can see the Child.prototype.constructor is set BACK to it's original constructor, just like you're doing in your example with the Person function.

JavaScript: Problem understanding how 'this' works in ES5 and ES6 [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
GIVEN:
var box5 = {
color: 'green',
position: 1,
clickMe: function() {
console.log{this)
}
}
The console.log = {color: "green", position: 1, clickMe: ƒ}
In other words pointing at the object "box5".
But add the following code:
document.querySelector('.green').addEventListener('click', function() {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
alert(str);
});
And you get the alert: "This is box number undefined and it is undefined"
Question: Why is 'this' apparently pointing at the object when I log it,
not when it try to print object values with "this.property"
There is the "hack" self = this and reference properties with self instead of this.
Probably because this is an HtmlElement, and an HtmlElement does not have a property called position or a property called color.
this is a representation of the object that called the current function. And if an event is fired, the callback function is called by the object the event happened to. In this case, an HtmlElement.
If you'd like to get values from an html element, you can try adding them to the dataset of the element. You can use Vanilla Javascript, and jQuery has their own method implementation
Javascript knows to make a this value present when a function is called while simultaneously dereferencing it off of an object. If a function is called, but not simultaneously dereferenced off an object, its this value will be the global object (window, in the case of browsers).
For example, consider this object:
let obj = {
name: 'amazing obj',
func: function() { console.log(this); }
};
If we now say:
obj.func();
We will see the console output obj itself.
But if we say:
let func = obj.func;
func();
We will see the console output the global object.
The difference between obj.func(), and func(), is that javascript sees that in obj.func's case the function is being dereferenced off of obj, and therefore makes obj the value for this.

Why is this inside an object window? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
Consider the following code:
var obj = {
x: this
}
obj.x turns out to be window. I thought this would refer to obj.
I don't understand how this works in the above situation. Even with late binding such as in JavaScript, shouldn't x refer to the obj object? I understand all other cases for this where its value is determined by how it is called in the code. Can someone please help me understand this behavior of this?
window is the default value for this if you run your code in a browser. As noted in the comments below, this will be undefined if 'use strict'; is in effect.
the value of this changes on the basis of the object where it resides.
example:
1
var test = {
a: 1,
b: function () {
console.log(this.a)
}
}
In this case the value of this will be the containing object.
var test = {
a: 1,
b: function () {
setTimeout(function () {console.log('surprise', this.a)}, 0)
}
}
This piece of code however doesn't give the same result.
Here without strict mode on, on a browser, property a will be accessed over the window.
The reason being the function in the setTimeout doesn't have the access to the object.
2
var someObject = {
value: 1,
someFunction () {
return function () {
console.log(this.value)
}
}
}
var displayValue = someObject.someFunction()
displayValue()
In this case too, this is undefined, as the value of this changes with respect to the object which contains the function being called.
someFunction is a method on the object someObject therefore, the value of this inside would be equal to someObject but the function returned by someFunction is not called by someObject hence the difference.
This refers to Current Execution Context which in this case (which is initial) is window object.
Check this out
More Specific to this question
One important principal about this is that:
this is not assigned a value until an object invokes the function where this is defined. Let’s call the function where this is defined the “this Function.”
So, lets assume you've defined your object this way:
var person = {
firstName :"John",
lastName :"Doe",
showHometown:function () {
console.log (this);
}
}
Since the this keyword is used inside the showHometown method, and the showHometown method is defined on the person object,​ this will have the value of the person object because the person object will invoke showHometown()​.
As you see difference between x in your defined object & mine, is who invokes them which is formally referred to Current Execution Context.

Understanding JavaScript function declaration syntax [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
After using JavaScript for a while, I came up with some questions.
The way to declare a function is:
var myFunction = function(param){//code here}
But there is also another way to declare a function which is
function myFunction(param){//some code}
What's the difference between the two methods to declare a function?
My second question is, I've understood that you can create an object from a function that's declared as:
function Person(name){this.name=name;}
And then, you can have another function declared like this:
function Speak(){console.log(this.name);}
How does the function Speak knows that it's related to the Person Object?
The first one is expression
var myFunction = function(param){//code here}
Second is declaration
function myFunction(param){//some code}
see this article
http://kangax.github.io/nfe/
When u use the word var, your'e declaring a variable realtive to where it's defined, and cannot be accesed from out wheres, and if its inside a function, it's destroyed at the end of the execution, and if you dont use it, you're defining on global ambit, and the variable still exists after the function execution.
The second thing is for programming OOP
Yo can use functions as same as it they were pure objects:
var person = {
name: null,
setName: function (name) {
this.name = name
}
}
Then you can access it's property
person.setName('john');
console.log(person.name);
in the shape of a function
function Person(name){
this.name = null;
}
var john = new Person('John');
console.log(john.name);
When you use this syntax:
function f1(){}
then f1 can be used everywhere in the current scope:
// we can call f1 even before definition of the function
f1(); // it works
function f1(){}
But, When we use this syntax:
var f1 = function(){};
then f1 is like as a pointer to an anonymous function which can be used after the point of assignment:
// we can't call it before assignment of our var
//f1(); // f1 is undefined here!
var f1 = function(){}
// we can call it here
f1(); // works
The second syntax is make more sense when you consider that every function is also an object. for example, we can have a function be a property of an object, like this:
var myObject = new Object();
myObject.say = function(x) {alert(x);};
// myObject now has a property/method named "say"
myObject.say("Hello");
About the second question: the this keyword. can you give the (outer) scope of your code which defines your Person and Speak functions? the code you wrote won't work as it is written. If you want to set proper reference for this in Speak function, you have to write something such as below:
function Person(name){ this.name=name; }
function Speak(){ alert(this.name); }
Person.prototype.DoSpeak = Speak; //here we attach DoSpeak to Speak function
var p = new Person("Saeed");
p.DoSpeak(); //this will work
Both are declaration
1) var myFunction = function(param){//code here}
This is a declaration that is assigned to 'myFunction' local variable
You can set an identifier for that function for debug or recursion purposes
var myFunction = function myFunctionIdentifier(param){ console.log(myFunctionIdentifier.toString())}
But to call this function you have to use 'myFunction ' variable
Another way to perform nested call is by using the arguments.callee that points to the function itself
var myFunction = function(param){ console.log(arguments.callee.toString())}
2) function myFunction(param){//some code}
This is a declaration that is assigned to the scope variable
in case you are in the global area it will be assign (for example in the browser) to the window object
So in fact window["myFunction"]() is valid
* About this question...
function Person(name){this.name=name;}
function Speak(){console.log(this.name);}
The reason that Speak 'knows' Person name is all about JavaScript scope.
Since both using the same scope, both functions 'speak' with the same this.
For example: if you code both functions in the global scope, this == window object thus
console.log(window['name']); will give you the name.
You don't want to code in that way .. since another function using this.name will override you existing logic.
If you will instantiate the Person entity
var person = new Person();
Then person variable will be this, this == person object
And the you can assign Speak in two or more ways:
inline:
function Person() {
...
this.Speak = function ...
}
outside the code, since person assign to (Person)this
person.Speak = function() ...
or the best way, use the prototype object:
Person.prototype.Speak = function() ...

What is 'this' referencing when it is inside a prototype? [duplicate]

This question already has answers here:
What does "return this" do within a javascript function?
(4 answers)
Closed 6 years ago.
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Stolen from Crockford's Good Parts. When the code returns 'this', what does 'this' reference in this case?
I always ask myself this when I see 'this' inside a js code because I know that js is funky with the word this (i.e. 'this' actually references the global variable when it is used inside a nested function)
As you are extending Function.prototype, this will refer to a function instance.
Example:
function foo() {};
foo.method(); // `this` refers to foo
There are like four different ways of calling functions, which determine what this refers to. MDN has a good article about it.
In short:
Simple function call: Global object (window in browsers)
Object method: The object (i.e. obj.method(), this references obj) (that's the case we have in your example)
Using the new keyword: An empty object, inheriting from the functions prototype
call / apply: Whatever you pass as first argument
In this context, this is a reference to the Function Instance.
this refers to the constructor Function that calls it's method method. So for example you can do this:
function Car(color){
this.color = color || 'blue';
}
Car.method('showcolor',function(){return this.color;});
//^Car is a constructor function, so 'this' in 'method' refers to Car here
var redcar = new Car('red'), yellowcar = new Car('yellow');
alert(redcar.showcolor()); //=> red
alert(yellowcar.showcolor()); //=> ... you guessed it!

Categories

Resources