如何在JS中传递和返回对象作为参数?

时间:2017-02-11 02:31:40

标签: javascript javascript-objects

我有一个接受对象的类,我想通过函数返回。但是,返回的类型是一个数字,我假设它是对象的引用。

class Sprite {
    constructor(img, x, y) {
        this._img = img;
        this._x = x;
        this._y = y;
    }

    get x() {
        return this._x;
    }

    setX(x) {
        this._x = x;
    }

    get y() {
        return this._y;
    }

    setY(y) {
        this._y = y;
    }

    get image() {
        return this._img;
    }
}

function main() {
    var gameCanvas = document.getElementById("gameCanvas");
    var avatarImage = new Image();

    avatarImage.src = "avatar.png";

    var avatar = new Sprite(150, 150, avatarImage);

   gameCanvas.getContext("2d").drawImage(avatar.image, avatar.x, avatar.y);
}

如何返回对象而不是引用?

console.log(typeof(avatar.image)); // prints number instead of object

1 个答案:

答案 0 :(得分:2)

你有一个错字

main {
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;
}



.first {
    background: #999999;
    flex-grow: 1;
    order: 1;
    margin: 20px;
    color: white;
    font-family: Arial, Helvetica, sans-serif; 

}


.second {
    background: #999999;
    flex-grow: 1;
    order: 3;
    margin: 20px;
    color: white;
    font-family: Arial, Helvetica, sans-serif; 

}





.third {
    background: #999999;
    flex-grow: 1;
    order: 3;
    margin: 20px;
    color: white;
    font-family: Arial, Helvetica, sans-serif; 

}



.fourth {
    background: #999999;
    flex-grow: 1;
    order: 3;
    margin: 20px;
    color: white;
    font-family: Arial, Helvetica, sans-serif; 

}



.first,.second,.third,.fourth{
    margin: 20px 20px;
    border-style: solid;
    border-color: black;
    border-width:  5px 5px 5px 5px;