This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Get property of object in JavaScript
var Terminal = function() {
this.walk = function() {
alert('hello');
}
this.go = 'walk';
this.move = 'walk';
}
var term = new Terminal();
var fn = 'walk';
if (term.hasOwnProperty(fn)) {
term.{fn};
}
How can I run the method term.walk() using the string 'walk'?
There are a couple of ways. The simplest is
term[fn]();
Or alternatively
var funcObj = term[fn];
funcObj.apply(term);
Use term[fn] to access the <fn> property of term.
All properties can be accessed using object["propertyname"]. Globally defined properties/methods can be called through window["propertyname"].
There's only one occasion where variables cannot be accessed through obj["prop_name"]:
function foo(){
var bar = 759;
//There is no "obj" where obj.bar exists.
}
Related
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:
Is it true that every function in JavaScript is a closure?
(2 answers)
Closed 7 years ago.
I have been reading about closure in JS and I wouldn't say I understand it perfectly but at least having some knowledge about it after reading a few examples and info from different sites but I can't really understand why one of these is a closure and not the other one.
Not closure function
var secret = "007";
function getSecret(){
var secret = "008";
function getValue(){
return secret;
}
return getValue();
}
getSecret();
Closure function
var secret = "007";
function getSecret(){
var secret = "008";
function getValue(){
return secret;
}
return getValue;
}
var getValueFun = getSecret();
getValueFun();
both of them has the same output as I can realize the first one that's not a closure returns the function invoked and the closure one just returns the function. This is the only difference I can think of and is this part of the reason why one of them is a closure and not the other one?
// You can try this:
var secret = "007";
function getSecret(){
var secret = "008";
var getValueFunc = function(){
return secret;
}
return {
getValue:getValueFunc
};
}
var getValueFun = new getSecret();
getValueFun.getValue();
This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);
This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 9 years ago.
I have been trying to learn OO JS. I was playing with different patterns, wrote following example.
var obj = function() {
this.a= function() {
return 'a';
}
}
obj.prototype.b = function() {
return 'b';
}
var instance = new obj();
console.log(instance.a());
console.log(instance.b());
Is there any difference here in function a and b?
this.a will be a separate function for every object you create:
var obj = function() {
this.a= function() {
return 'a';
}
}
obj.prototype.b = function() {
return 'b';
}
var instance1 = new obj();
var instance2 = new obj();
console.log(instance1 === instance2); // false: different instances
console.log(instance1.a === instance2.a); // false: different functions (this.a)
console.log(instance1.b === instance2.b); // true: obj.prototype.b
This means that this.a = function(){ ... } will consume memory for every instance, something you most likely want to avoid.
In your code, a is a function of the instance, whereas b is a function of the class.
In terms of them actually working, there isn't much different between them by themselves. However, let's say you put var test = 123; inside the obj function. a will be able to access it, but b will not.
Additionally, you can overwrite instance.a with another function, and it will only affect the current instance.
On the other hand, a is a separate function object for each instance of the object. This could become a problem in terms of memory use if you have large numbers of instances.
This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 9 years ago.
So, I am not a JavaScript expert, just trying to understand what the difference is between two following snippets of code. I have a project that I want to convert to TypeScript and I need to understand the difference between two code snippets being generated.
var Pony = (function () {
function Pony() { }
Pony.prototype.bite = function () {
alert("Chomp!");
};
return Pony;
})();
var Pony2 = (function () {
function Pony2() {
var self = this;
self.bite = function () {
alert("Chomp!");
};
}
return Pony2;
})();
The difference between the two is that you can get to the prototype of the first Pony via attributes on the object stored in var Pony and could expand upon or use the associated bits of that prototype elsewhere where as Pony2 would just be considered a function. So if you do not plan on using any sort of prototypical inheritance later on they are equivalent.
The answers above give a good overview on the difference between putting on the prototype and putting on the instance. As to your question about converting to TypeScript, below is how you would write them both:
class Pony {
bite(){
alert('chomp');
}
}
class Pony2 {
bite: () => void;
constructor(){
this.bite = () => alert('chomp');
}
}
As far as how you use them, there's no difference. However, from a performance standpoint the former method would be preferable. Let's extend your example a little bit:
var prototypePony1 = new Pony();
var prototypePony2 = new Pony();
var thisPony1 = new Pony2();
var thisPony2 = new Pony2();
prototypePony1.hasOwnProperty('bite'); //returns false
prototypePony2.hasOwnProperty('bite'); //returns false
thisPony1.hasOwnProperty('bite'); //returns true
thisPony2.hasOwnProperty('bite'); //returns true
Pony.prototype.bite = function() { alert('Nomnomnom!'); };
Pony2.prototype.bite = function() { alert('Nomnomnom!'); };
prototypePony1.bite(); //alerts 'Nomnomnom!'
prototypePony2.bite(); //alerts 'Nomnomnom!'
thisPony1.bite(); //alerts 'Chomp!', instance property is accessed first
delete thisPony2.bite;
thisPony2.hasOwnProperty('bite'); //returns false
thisPony2.bite(); //alerts 'Nomnomnom!'
In the example above, thisPony1 and thisPony2 both get their own copy of the bite function, since it was defined using this However, prototypePony1 and prototypePony2 both share the same copy of bite from Pony's constructor.
Once we define the bite prototype on Pony2, the instance property is still accessed first on thisPony1. It's not until we delete the instance property that we see the newly defined prototype property on thisPony2.
For more detailed info on defining object methods, have a look here.