有很多方法可以用JavaScript调用函数,但是由于某种原因,这对我不起作用。有人可以告诉我我到底在做什么错吗?

我尝试进行原型制作(例如gameObject.prototype = {};),但是由于某种原因,该方法无效。现在,我只是尝试直接在函数中分配方法,而这甚至都不起作用。

这幅画怎么了?

function gameObject(){
            this.o={};
            this.setimage=function(i){
                this.o.img=i;
            };
            this.setDimensions=function(w,h){
                this.o.width=w;
                this.o.height=h;
            };
            this.setPosition=function(x,y){
                this.o.x=x;
                this.o.y=y;
            };
            this.create=function(){
                var el=document.createElement("div");
                el.className="object "+this.o.cname;
                el.style.width=width*this.o.w;
                e.style.height=height*this.o.h;
                el.style.position="absolute";
                el.style.top=height*this.o.y;
                el.style.left=width*this.o.x;
                map.appendChild(el);
            };
            this.setClass=function(c){
                this.o.cname=c;
            };
            return this.o;
        }


我想要的是这样的:

var d=new gameObject(); d.setClass("class"); d.setDimensions(0.8,0.15);


等等等等

我对面向对象的编程还很陌生,所以我什至不知道我的词汇是否正确。我正在尝试做什么,准确地做到这一点的正确方法是什么?

最佳答案

您不应该从此构造函数返回任何信息。

删除这个

返回this.o;

Demo here
如果从构造函数返回值,则创建的对象将具有返回值的类型。

Demo here
如果看到此演示,则d.a返回4表示new gameObject返回了this.o值,而不是this

如果要使用原型

function gameObject(){
    this.o={};
}

gameObject.prototype = {
    setimage:function(i){
        this.o.img=i;
    },
    setDimensions:function(w,h){
        this.o.width=w;
        this.o.height=h;
    },
    setPosition:function(x,y){
        this.o.x=x;
        this.o.y=y;
    },
    create:function(){
        var el=document.createElement("div");
        el.className="object "+this.o.cname;
        el.style.width=width*this.o.w;
        e.style.height=height*this.o.h;
        el.style.position="absolute";
        el.style.top=height*this.o.y;
        el.style.left=width*this.o.x;
        map.appendChild(el);
    },
    setClass:function(c){
        this.o.cname=c;
    }
}


Demo here

07-24 18:54
查看更多