1

I define an object called anotherObject with a function called anotherFunction based on the someFunction from the object someObject.

 var someObject={
 someFunction:function(){
     return this;
 }
};

console.log(someObject.someFunction()===someObject);//true

var someFunc=someObject.someFunction;
console.log(someFunc===someObject.someFunction);//true
//the function does not have the same context as that of the function called earlier...
console.log(someFunc()===someObject);//false

var anotherObject={
 anotherFunction:someObject.someFunction
};

console.log(anotherObject.anotherFunction===someObject.someFunction);//true
console.log(anotherObject[anotherFunction]()===anotherObject);//true;
console.log(anotherObject.anotherFunction()===someObject);//false

Firefox Scratchpad reports that the function anotherFunction is not defined.

vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

1 Answers1

0

That's the way JavaScript functions actually work, the someFunction is a function which its responsibility is to return the this in the current context, no matter what is for this one:

var someFunc=someObject.someFunction;

you can call it using call or apply with whatever context you like:

var myobj = {};
console.log(someFunc.call(myobj)===myobj);//true
console.log(someFunc.apply(myobj)===myobj);//true

no matter what you pass as the first argument in call and apply, your function would return that very object. So as you see your function does what it is supposed to do, but if you want it to always return your first object someObject, you do not need to use this keyword.

Read my answer to the How does JavaScript .prototype work?, I have tried to dig into this concept in the first two parts.

And also this is one of the best resources you can find about this concepts:

Understanding JavaScript Function Invocation and “this”

Community
  • 1
  • 1
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • I would like to know why the function `someObject.someFunction` was not copied to `anotherObject.anotherFunction`.I do understand a little bit about call and apply – vamsiampolu Mar 01 '14 at 08:05
  • 1
    @user2309862: what do you mean by `was not copied`? when you create your fucntion like `anotherFunction: someObject.someFunction`, it just creates a reference to the original function. – Mehran Hatami Mar 01 '14 at 08:16
  • you are saying that adding a property to a function which has been passed to a higher order function would modify the original function – vamsiampolu Mar 01 '14 at 11:12