-1

Same code but getting access error on one code block.

//Getting undefined error 
//output: Hi Mark, my name is undefined
var john = {
  sProp: 'John',
  greet: function(person) {
    alert("Hi " + person + ", my name is " + this.sProp);
  }
};
var fx = john.greet;
fx("Mark");



// no undefined error 
// output is " Say hito allsome string value "

var myObject = {
    sProp: 'some string value',
    numProp: 2,
 callme:function(arg){
  alert("Say hi" + arg + this.sProp); 
 }
};
myObject.callme('to all');
Bharanikumar
  • 25,457
  • 50
  • 131
  • 201
  • 2
    Possible duplicate of [How does "this" keyword work within a JavaScript object literal?](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal) – JJJ Feb 01 '16 at 10:02
  • @JamesThorpe for all all questions, there is a answer in stack, you can see lots of thread comments possible duplicate, every developer looking solution for their prob, might be they are not much intelligent like James and Juhana ignore my ignorance. i apologizes for the disturbance – Bharanikumar Feb 01 '16 at 10:13

1 Answers1

3

The problem in your question is this:

var fx = john.greet;
fx("Mark");

When you affect john.greet to a var like this, the calling context becomes: window.

If you want to keep the context, you have to either use: bind or call the function immediatly with the owning object.

var fx = john.greet.bind(john)
fx("Mark")

Or

john.greet("Mark")
Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99
  • For : var fx = jonh.greet.bind(jonh); fx("Mark"); ReferenceError: jonh is not defined http://localhost/js/oojs.html Line 22 – Bharanikumar Feb 01 '16 at 10:19