Say, I have two functions:
function foo() {
this.lorem = 'ipsum';
}
function boo() {
console.log(this.lorem);
}
And I want to insert the boo function at the end of the foo function so that they can share the same this. How would I do it?
5 Answers 5
Like this?
function foo() {
this.lorem = 'ipsum';
console.log(this.lorem);
}
In all seriousness, your question is not clear enough to be reliably answered.
answered Aug 17, 2011 at 10:58
Delan Azabani
81.8k30 gold badges174 silver badges215 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
In the event you want to keep them separate:
function foo() {
this.lorem = 'ipsum';
boo(this);
}
function boo(element) {
console.log(element.lorem);
}
answered Aug 17, 2011 at 10:58
m.edmondson
31k29 gold badges129 silver badges212 bronze badges
Comments
Wrap them both under the same context:
var myClass = {
foo: function foo() {
this.lorem = 'ipsum';
this.boo();
}, boo: function boo() {
alert(this.lorem);
}
};
Then to activate foo:
myClass.foo();
answered Aug 17, 2011 at 11:03
user447356
2 Comments
Delan Azabani
That's not a class, that's an object.
knittl
I think you meant
foo: function() { ... } ;)function foo() {
this.lorem = 'ipsum';
boo.call(this);
}
function boo() {
console.log(this.lorem);
}
foo();
answered Aug 17, 2011 at 11:05
evilcelery
16.1k8 gold badges45 silver badges55 bronze badges
Comments
If you don't want to modify the existing functions do this:
function foo() {
this.lorem = 'ipsum';
}
function boo() {
console.log(this.lorem);
}
function bar() {
boo.call(new foo);
}
bar();
Here's a JSFiddle of it in action: http://jsfiddle.net/8Wb6T/
answered Aug 17, 2011 at 11:27
evilcelery
16.1k8 gold badges45 silver badges55 bronze badges
Comments
lang-js
thisactually refers to. It refers to thewindowobject. You are makingloremglobal. There is no "sharing" ofthisinvolved. In both functionsthisalready refers to the same object (window). Evenfoo(); console.log(this.lorem);would work.