Access Object AND property of object using variables in Javascript [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I am aware you can access properties of objects in javascript using variables like this Object['property'] but I want to access the Object using a variable too.
// The object and his function
var Foo = {};
Foo.bar = function() { console.log("I am a useful function dood"); }
// The accessors
var obj = 'Foo';
var method = 'bar';
But when I try it in the way I think is right, I get the following. As all links in the world seem to be about accessing object properties with variables I don't seem to be able to sift one out that accesses objects like this too.
typeof obj // "object"
typeof Foo[method] // "function"
typeof [obj].foo // undefined
typeof [obj][method] // undefined <-- This is what I'm trying to use
Am I able to access the object like this?
EDIT
According to answers, if the object is globally scoped I could use window[obj][method] but the above is contained in an immediately invoked function like this:
(function(){
// The stuff from above...
})();
Will this work I will have to put this into an identifiable var that is globally scoped?
PS I will never ever use eval();

If your Foo object is at the global object then :
window[obj][method]() //I am a useful function dood`
Else , you will need to supply more info.

Related

Why do I need to bind a shadowed function that is called through the same object? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Why call function in window scope is different from object scope [duplicate]

This question already has answers here:
Using the variable "name" doesn't work with a JS object
(4 answers)
Closed 5 years ago.
Why calling Person in window scope is returning "[Object Object]" while call that in object scope is returning Object.
global window object already have a property of name, and it's inside the scope of native code.
https://www.w3schools.com/jsref/prop_win_name.asp
window.name is a getter/setter to set the name of the window. As such, it has to be of type string.
Try this:
window.name = ["something", "else"];
You will see that now window.name is set to "something,else"; which is the result of Array.toString().
This is exactly what is happening here. When you call an object's toString, you get [object Object].
Your program works fine if you do not use the predefined window.name getter/setter.
function Person(first, last) {
this.something = {
first,
last
};
}
f = {};
Person.call(f, "fsd", "fsd");
console.log(f.something);
g = window;
Person.call(g, "fsd", "fsd");
console.log(g.something);
More on getter/setters in javascript:
Setters: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/set
Getters: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/get

Different ways of defining unassign variable in javascript [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 6 years ago.
I know when we want to define unassign variable in Javascript we can do:
var p;
and the other:
var p ={};
i want to know differences between these two ways, and if i define a variable in second way it is not null! what is the value in the variable, if we want using it in a if condition, for example :
var p ={};
if(p=='what i shout put there')
{}
var p is creating an unassigned variable. So console.log(p) will log undefined
var p ={}; is a way of creating object using literal notation.
Object p have methods like constructor,hasOwnProperty,toLocaleString etc
if(p=='what i shout put there'){}
If it is required to check if p is an object then below snippet is useful
if(Object.prototype.toString.call( a ) === '[object Object]'){
// Do rest of code
}
An object can have properties. like
var p={};
p.a ="someValue";
In this case you can check by
if(p.a === 'someValue'){
// Do rest of code
}
var p = {};
It is not unassigned ,it is infact assigned to the empty object
If you do below , it will be trut
if(p) {} // truthy

Javascript object creation practices [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
This is what I think is best for making an object in js
function obj(){
var x = "hi";
this.getX(){return x;}
}
var y = new obj()
console.log(y.x); //this returns undefined
But from what I have seen, using this.variable is used more often in object creation.
I am thinking in java where things should be "private" in a class (note I have read about closures), does that apply in js?
What is considered the best way of object creation?
It sounds like you're trying to apply Java concepts to JavaScript, but things works completely differently in JS. You should check out the MDN article on JavaScript closures.
var variables exist in the closure. They are accessible from any function declared in the same scope.
var me = 'hello';
function someFunction() {
console.log(me);
}
someFunction(); //prints 'hello' to console
this variables will be directly accessible, even outside the scope, in the resulting object.
function someFunction() {
this.me = 'hello';
}
var instance = new someFunction();
console.log(instance.me); //prints 'hello' to console

Create variable name based on argument sent to function in javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I wanted to create variable name based on value sent to function in javascript.
like following, when i call function variable : variable("zebra"); this should return variable name as zebra1
function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
Try:
window['zebra'] = 'abc';
The window object holds all the global variables, assuming this is a request for global variables.
To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.
Alternatively, you could create a global (or local) object named variables to hold all your variables:
function whoknows() {
var variables = {};
variables['zebra'] = 'abc';
}
Read more on working with objects at mozilla.org
You can create global variable with
window["zebra"] = "abc";
and use later ether with the same indexer syntax or directly - zebra.

Categories