あなたはconsole.log(b.getX)、
まず、関数を実行するのではなく、その内容をログに記録します。次に、関数は var bのプロパティではありません。
// create the function.
b.getX = function()
{
this.x;
};
// runs the command.
b.getX();
編集:
あなたが間違ったことを説明する Jsfiddle:
http://jsfiddle.net/kychan/zsWpN/
編集2:
まず、「プロパティ」とは何かを説明します。プロパティは、特定のオブジェクトが所有する「もの」です。var を定義してインスタンス化しましょう。
var x = {}; // this makes an object.
プロパティを追加することもできます。
var y = {myProp1:'Hello', myProp2:'World'};
これにより、2 つのプロパティ (myProp1 と myProp2) を持つオブジェクト (y) が作成されます。
ここで、コード (jsfiddle) に (グローバル) 関数 getX があります。これはプロパティとして設定されていないため、グローバル ステートメントとして呼び出す必要があります。
getX(b); // should return this.x;
より完全な説明をいじる: 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!