向JavaScript函数添加方法

Ric*_*der 1 javascript oop methods function

有许多方法可以在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;
        }
Run Code Online (Sandbox Code Playgroud)

我想要的是这样的:

var d=new gameObject(); d.setClass("class"); d.setDimensions(0.8,0.15);
Run Code Online (Sandbox Code Playgroud)

等等

我仍然是面向对象编程的新手,所以我甚至不知道我的词汇是否正确.我正在尝试做什么,以及正确的方法是什么?

Aru*_*hny 5

您不应该从此构造函数返回任何内容.

删除它

    返回this.o;

在这里演示.

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

在这里演示.如果您看到此演示d.a返回4意味着new gameObject返回this.o值而不是this其中的值gameObject().

如果你想使用原型

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里演示.