This question already has answers here:
Node.js: What is the context of the `this` operator when used in module scope? [duplicate]
(3 answers)
Closed 5 years ago.
the declaration of variable name = michelle in global scope is not being recognised by function sayNameForAll(), please let me know what is the issue.
function sayNameForAll() {
console.log(this.name);
}
var person1 = {
name: "Nicholas",
sayName: sayNameForAll
};
var person2 = {
name: "Greg",
sayName: sayNameForAll
};
var name = "Michael";
person1.sayName();
person2.sayName();
sayNameForAll();
this is the output of my code
It is working as expected in this script, the this variable can be changed in three ways:
when you call it inside of an object in that case would get the
object .
When you use a constructor, class function.
And when you use call(), apply(), or bind(); methods.
Other wise will get the global object...
function sayNameForAll() {
console.log(this.name);
}
var person1 = {
name: "Nicholas",
sayName: sayNameForAll
};
var person2 = {
name: "Greg",
sayName: sayNameForAll
};
var name = "Michael";
person1.sayName();
person2.sayName();
sayNameForAll();
The issue is within the context you run your function. In 2 first runs it goes inside context of the object, where you have 'this' internal variable. For the last one - you're trying to output 'this.name' but inside you've had only 'name'
Related
I am learning javascript and i came across a doubt. Why is the value of "this" undefined in the first example , but prints out correctly in the second.
example 1:
var myNamespace = {
myObject: {
sayHello: function() {
console.log( "name is " + this.myName );
},
myName: "john"
}
};
var hello = myNamespace.myObject.sayHello;
hello(); // "name is undefined"
example 2:
var myNamespace = {
myObject: {
sayHello: function() {
console.log( "Hi! My name is " + this.myName );
},
myName: "Rebecca"
}
};
var obj = myNamespace.myObject;
obj.sayHello();//"Hi! My name is Rebecca"
Why does the value of "this" changes within the function. What concept am i missing?
First case you are just getting the reference of the function to the vairable hello, and invoking it from global context (window in browsers, global in node), So this becomes what invoked the function except for (bound functions). You can always set the context explicitly using function.call or set the context explicitly to the function using Ecma5 function.bind
hello.call(myNamespace.myObject); //now you are setting the context explicitly during the function call.
or just bind it while getting the function reference.
var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject); //Now no matter where you call it from `this` will point to the context of myObject
Second case you are invoking it from the object itself so this points to the object.
In the first case, the implicit this object is the global scope. Because there is no myName in the global scope, you get undefined.
If you want a free function with the proper this, use bind:
var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject);
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.
This question already has answers here:
JavaScript private methods
(34 answers)
Closed 6 years ago.
I want function to be available on a object, but I don't it to be visible if if I console.log it or send it to another function.
var obj = function() {
this.name = 'Bob';
this.age = 23;
}
obj.prototype.say = function() {
console.log(this.name, this.age, 'thats me..');
}
var pers = new obj();
console.log(pers); // { name: 'Bob', age: 23 }
pers.say(); // Bob 23 thats me..
Would this be good for solution and good practice for that? Or is it a better way to accomplish this in javascript?
Functions created by using prototype would also be visible when you log the object. The only thing you can do at this context is to create functions in your constructor using this and create a closure. And these functions will not be a shared functions among the object instances unlike prototypal functions. I mean, the function's change will not be reflected in all object instances.
var obj = function() {
this.name = 'Bob';
this.age = 23;
function privateTest(){ alert("hai"); }
this.test = privateTest;
}
This question already has answers here:
How do JavaScript closures work?
(86 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
function Person(name) {
Object.defineProperty(this, "name", {
get: function () {
return name;
},
set: function (newName) {
name = newName;
},
enumerable: true,
configurable: true
});
this.sayName = function () {
console.log(this.name);
};
}
var person1 = new Person("Nicholas");
var person2 = new Person("Greg");
console.log(person1.name); // Nicholas
console.log(person2.name); // Greg
person1.sayName(); // Outputs "Nicholas"
person2.sayName(); // Outputs "Greg"
How is that the accessor property name can use the named parameter name to store its value? Isn't a local variable garbage-collected after the execution of its containing context (in this case, the Person constructor)?
This question already has answers here:
Closed 10 years ago.
What's the difference between these?
var person = {
age: 25,
name: "David"
};
var person = (function() {
var name = "David", age = 25;
}());
My question really is, what does (function(){}()) do?
What does (function(){}()) do?
This essentially creates an anonymous function and then executes it. One common use for this is limiting global variables.
For example, the following would have three global variables (var1, var2, and var3):
var var1 = "a", var2 = "b", var3 = "c";
If you wrapped these declarations in the anonymous function, they're still accessible as local variables within the anonymous function, yet do not cloud up the global namespace. For example:
(function() {
var var1 = "a", var2 = "b", var3 = "c";
console.log(var1); // interact with local variables
})(); // execute function.
What's the difference between these?
var person = {
age: 25,
name: "David"
};
If this code is contained in a function, it creates a local variable named person. Otherwise, it creates a global variable named person.
var person = (function() {
var name = "David", age = 25;
}());
This code creates and executes an anonymous function, then assigns the return code of that anonymous function to the variable person. Since the anonymous function has no return value, the variable person has a value of undefined. This statement, as it currently stands, is functionally equivalent to var person;, because the anonymous function has no side-effects and doesn't have a return value.
var person = (function() {
var name = "David", age = 25;
}());
person will be undefined, because the function doesn't have a return statement.
It is just a self executing anonymous function, you could image that as below.
function foo() {
var name = "David", age = 25;
}
var person = foo();
It executes the anonymous function you just created.
This technique is useful because it allows you to scope member in your class.
If you're looking for a good way to do classes and inheritance, take a look at http://ejohn.org/blog/simple-javascript-inheritance/
I'd also recommend defining your classes as AMD modules.