为什么我的函数返回undefined

Why does my function return undefined?

本文关键字:undefined 返回 函数 我的 为什么      更新时间:2023-09-26

使用easeljs和box2d,我创建了几个相互碰撞的对象。使用以下代码,我在屏幕上创建了一个框:

var b = new Box(400,0); // pass xPos and yPos
stage.addChild(b.view);

在我的剧本中的某个点上,盒子与一个圆碰撞,当这种情况发生时,一个三角形必须朝着盒子推。所以我需要盒子的位置!在我的Box.js中,我有以下功能:

function getX(){
    var xPos = this.body.GetPosition().x * SCALE;
    return xPos;
}

我已经将相同的功能替换为以下功能:

function getX(){
    return this.x;
}

当我使用未定义的console.log(b.getX);到浏览器控制台时,这两个函数都返回相同的值。我需要在返回函数中传递参数吗?或者函数的结构不正确吗?

您说的是console.log(b.getX),

首先,您不是在执行函数,而是在记录它的内容。其次,函数不是varb的性质。

// create the function.
b.getX = function()
{
 this.x;
};
// runs the command.
b.getX();

编辑:

Jsfidle解释你做错了什么: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!

加上Kai的例子,我终于成功了!所以,谢谢凯!我使用了他在最后一次编辑中展示的第三种方法,在我的box函数的tick函数中添加了一个变量。以下是我所做的:

在我的Box.js中,我用box2d创建了一个b2_staticBody,并给它一个getX函数,它返回盒子的x位置。

this.getX = function(){
    return boxX;
}

我的tick函数(使用easeljs创建)会更新盒子的位置,所以在这里我将box.x保存到一个名为boxX的var中。

function tick(e){
    boX = this.body.GetPosition().x * SCALE;
    this.x = this.body.GetPosition().x * SCALE;
    this.y = this.body.GetPosition().y * SCALE;
    this.rotation = this.body.GetAngle() * (180/Math.PI);
}

现在,我可以在创建盒子后调用b.getX();函数了。

b = new Box(350,450); // x and y position
stage.addChild(b.view);
var targetX = b.getX();
console.log(targetX);

再次感谢Kai帮助我理解如何解决我的问题,并理解使用属性等。