You are saying console.log(b.getX),
first, you are not executing the function but logging its content. Secondly, the function is not a property of var b.
// create the function.
b.getX = function()
{
this.x;
};
// runs the command.
b.getX();
Edit:
Jsfiddle explaining what you did wrong: http://jsfiddle.net/kychan/zsWpN/
Edit 2:
First i'll explain what a 'property' is. An property is a 'thing' owned by a certain object. Let's define a var and instantiate it:
var x = {}; // this makes an object.
We can also add properties with it:
var y = {myProp1:'Hello', myProp2:'World'};
This creates an object (y) with two properties (myProp1 and myProp2).
Now, in your code (jsfiddle) you have the (global) function getX. This isn't set as a property, thus it must be called as a global statement:
getX(b); // should return this.x;
Fiddle with more thorough explanation: http://jsfiddle.net/kychan/WwxC9/
// METHOD 1 (Your method); works, but you can do it more directly, see METHOD 2.
// define the var, with 'var'.
// let it hold a (global) function.
var getX = function(object){
return object.x;
};
// we make a test variable holding an object with property x:
var foo = {x:4};
console.log(getX(foo)); // this should return 4.
// METHOD 2:
// we will make a normal function (which has the same execution as METHOD 1).
function getX2(o)
{
return o.x;
}
// create a test variable.
var bar = {x:4};
console.log(getX2(bar)); // should print 4 as well.
// METHOD 3:
// now we create a CLASS which has a default property named getX:
function myObject()
{
this.x = 4;
// here, this is called a method (because it is a property owned by a class/object).
this.getX = function()
{
return this.x;
};
}
// we create a test variable holding the object from the class myObject.
var baz = new myObject();
console.log(baz.getX()); // now it ALSO should print 4!