你说的是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'};
这将创建一个具有两个属性(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!