var obj = {
someFunc : function() {
console.log("Hello");
console.log(this);
var obj1 = {
someFunc1 : function() {
console.log("Hi");
}
};
}
};
obj.someFunc();
obj.obj1.someFunc1();
I have just created an object. And inside an object, a method, and then a new object and obj1. I am just trying to check 'this' keyword. But, it seem to me it's grammatical error in js. That is not possible. Right? But, why?
var obj = {
someFunc : function() {
console.log("Hello");
console.log(this);
return {
someFunc1 : function() {
console.log("Hi");
}
};
}
};
obj.someFunc().someFunc1();
Related
Given the following how do i enable this to work correct?
return {
methodA: function() {
return methodB();
},
methodB: function() {
alert("hi");
}
}
You need to reference the context, via this.
var foo = {
methodA: function() {
return this.methodB(); //context
},
methodB: function() {
alert("hi");
}
}
foo.methodA(); //alerts "hi"
It seems you are returning from a module like function. The safe way is not to use this, it is to keep a reference to the object so that it won't matter how the function is called.
function getObj() {
var obj = {
methodA: function() {
return obj.methodB();
},
methodB: function() {
alert("hi");
}
};
return obj;
}
var myObj = getObj();
// Works
myObj.methodA();
// Works but would not work if you were using `this` as suggested by Utkanos.
someDomElement.addEventListener('click', myObj.methodA);
my problem seems to be that my object function is not visible if i call it from within an object of functions. Example Code:
function foo()
{
this.bar = function()
{
alert("hit me!");
}
this.sna = {
fu: function ()
{
this.bar();
}
};
}
this seems to refer to sna instead of foo. How do i adress foo? this.parent does not work.
Use a variable to refer to this(Foo). See this - JavaScript | MDN
function Foo() {
this.bar = function() {
console.log("hit me!");
};
var that = this;
this.sna = {
fu: function() {
that.bar();
}
};
}
var foo = new Foo();
foo.bar();
foo.sna.fu();
One option is to add a reference to this:
function foo() {
var _t = this;
this.bar = function() { };
this.child = {
this.foo = function() {
_t.bar():
};
};
}
I have the following object:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
myFunc(); // Says myFunc is not defined.
});
}
}
object.initialize();
How do I access myFunc or attr1 from inside of the anonymous function passed to addEventListener?
One way I can think of is this:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
myObject = this;
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
alert(myObject.attr1);
// calling myFunc
myObject.myFunc();
});
}
}
object.initialize();
But is this a good solution?
Also, If I do this:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
myFunction = this.myFunc;
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
alert(myObject.attr1);
// calling myFunc
myFunction();
});
}
}
object.initialize();
Then it alerts with "undefined". Which means this.attr1 is undefined.
Why so?
Inside your event handler function, this will always refer to the DOM element on which the event has been attached.
To access the object properties, you need to use the alternatives such as self/that.
initialize : function() {
var that = this;
document.getElementById("myElem").addEventListener("click", function() {
alert(that.attr1);
that.myFunc();
});
}
In your solution, you have declared myObject globally as var is missing.
var object = {
attr1 : "hello",
myFunc : function() {
alert("Instance of window ? "+(this instanceof Window));
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
myFunction = this.myFunc;
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
alert(object.attr1);
// calling myFunc
myFunction();
});
}
}
object.initialize();
<div id="myElem">Click me</div>
Now as you can see in the alert, this refers to the window object. Because when you copy the function, its by value and not by reference. So only the function is copied and not underlying object. So now this will refer to the window object.
The solution you provided is exactly how I go about solving this issue, declare a variable and set its value to this, then use that to call other functions within your object.
otherFunc: function() {
console.log('test');
},
myFunc: function() {
var self = this;
// do stuff
// call other function
self.otherFunc();
}
Just make it like this - >
You do not need extra variables to make your code so obscure. :)
var object = {
attr1: "hello",
myFunc: function () {
alert(this.attr1); //This should alert "hello"
},
initialize: function () {
document.getElementById("myElem").addEventListener("click", function () {
// How do I access attr1 from here?
object.myFunc();
});
}
}
object.initialize();
I originally had code like that below, where I had nothing in the global namespace and I was able to call functions in obj2 from obj1 and vice versa. And all was well.
(function() {
var obj1 = {
obj1_f1 : function() {
},
obj1_f2 : function() {
obj2.obj2_f1();
}
};
var obj2 = {
obj2_f1 : function() {
obj1.obj1_f1();
},
obj2_f2 : function() {
}
};
$(document).ready(function () {
obj1_f1();
});
})();
But now I need to call a function in the obj1 object from the global context, so I have to introduce a global object:
var com_mycompany_make_sure_unique = new function() {
// use 'this.' so that obj1 is not in the global namespace
this.obj1 = {
obj1_f1 : function() {
},
obj1_f2 : function() {
com_mycompany_make_sure_unique.obj2.obj2_f2();
}
};
this.obj2 = {
obj2_f1 : function() {
com_mycompany_make_sure_unique.obj1.obj1_f1();
},
obj2_f2 : function() {
}
};
$(document).ready(function () {
com_mycompany_make_sure_unique.obj1.obj1_f1();
});
};
but I'm not overly happy with that - I have to prepend all function calls with my global object name when calling functions across obj1 and obj2. I think I'm missing a trick.
Thanks for any help,
Paul
You can do this (see comments):
var com_mycompany_make_sure_unique = function() {
// Continue using variables as you were before
var obj1 = {
obj1_f1 : function() {
},
obj1_f2 : function() {
obj2.obj2_f2();
}
};
var obj2 = {
obj2_f1 : function() {
obj1.obj1_f1();
},
obj2_f2 : function() {
}
};
$(document).ready(function () {
obj1.obj1_f1();
});
// Return an object that can be used via the `com_mycompany_make_sure_unique` variable
return {
obj1: obj1,
obj2: obj2
};
}();
This is sometimes called the "revealing module pattern" because everything inside the outer anonymous scoping function is private, and then you "reveal" the parts you want to reveal by putting them on the object you return. If you only needed to expose obj1, for instance, and not obj2, you could do that:
return {
obj1: obj1
};
My question, though, is why do you need to call functions from the global context? With modern event handling and Asynchronous Module Definition loaders like RequireJS, the only global you should really require (ugh) is the AMD function(s).
Side note: I replaced your var ... = new function() { ... }; with var ... = function() { ... }(); There's no need to use new here, and doing so can tend to confuse people (and gives the resulting object an extra prototype it doesn't need). But you could use your original form if you like, just change the end to
this.obj1 = obj1;
this.obj2 = obj2;
...rather than returning an object.
I've an object looks like this:
var obj ={
property : '',
myfunction1 : function(parameter){
//do stuff here
}
}
I need to set some private properties and functions, which can not be accessed/seen from outside of the object. It is not working with
var property:, or var myFunction1
Next question is, if I call a function within or outside the object, I always have to do this with obj.myfunction(). I would like to asign "this" to a variable. Like self : this. and call inside the object my functions and variables with self.property and self.myfunction.
How? :)
There are many ways to do this. In short: If dou define a function inside another function, your inner function will be private, as long as you will not provide any reference to if.
(function obj(){
var privateMethod = function() {};
var publicMethod = function() {
privateMethod();
...
};
return {
pubMethod: publicMethod
}
}());
var obj = (function() {
var privateProperty;
var privateFunction = function(value) {
if (value === void 0) {
return privateProperty;
} else {
privateProperty = value;
}
};
var publicMethod = function(value) {
return privateFunction(value);
}
return {
getPrivateProperty: function() {
return privateFunction();
},
setPrivateProperty: function(value) {
privateFunction(value);
}
}
})();
obj.setPrivateProperty(3);
console.log(obj.getPrivateProperty());
// => 3
console.log(obj.privateProperty);
// => undefined
obj.privateFunction();
// => TypeError: undefined is not a function
Use closures. JavaScript has function scope, so you have to use a function.
var obj = function () {
var privateVariable = "test";
function privateFunction() {
return privateVariable;
}
return {
publicFunction: function() { return privateFunction(); }
};
}();