0

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?

asked Aug 17, 2011 at 10:56
1
  • 1
    I don't think you understand what this actually refers to. It refers to the window object. You are making lorem global. There is no "sharing" of this involved. In both functions this already refers to the same object (window). Even foo(); console.log(this.lorem); would work. Commented Aug 17, 2011 at 12:11

5 Answers 5

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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();

Live test case.

answered Aug 17, 2011 at 11:03

2 Comments

That's not a class, that's an object.
I think you meant foo: function() { ... } ;)
0
function foo() {
 this.lorem = 'ipsum';
 boo.call(this);
}
function boo() {
 console.log(this.lorem);
}
foo();
answered Aug 17, 2011 at 11:05

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.