相关疑难解决方法(0)

如何在JavaScript中"正确"创建自定义对象?

我想知道创建一个具有属性和方法的JavaScript对象的最佳方法是什么.

我已经看到了这个人在所有函数中使用var self = this然后使用的示例,self.以确保范围始终正确.

然后我看到了使用.prototype添加属性的示例,而其他人则使用内联方式.

有人可以给我一个具有一些属性和方法的JavaScript对象的正确示例吗?

javascript

464
推荐指数
7
解决办法
13万
查看次数

为什么我不使用Child.prototype = Parent.Prototype而不是Child.prototype = new Parent(); 对于Javascript继承?

我不明白javascript中继承的这种行为我总是看到它定义如下:

function GameObject(oImg, x, y) {

    this.x = x;
    this.y = y;
    this.img = oImg;

    this.hit = new Object();
    this.hitBox.x = x;
    this.hitBox.y = y;
    this.hitBox.width = oImg.width;
    this.hitBox.height = oImg.height;

}

Spaceship.prototype = new GameObject();
Spaceship.prototype.constructor = Spaceship;

function Spaceship(){
    console.log("instantiate ship");
    GameObject.apply(this, arguments);
    this.vx = 0;
    this.vy = 0;
    this.speed = 3;
    this.friction = 0.94;
}
Run Code Online (Sandbox Code Playgroud)

但就我而言,这些线路:

    this.hitBox.width = oImg.width;
    this.hitBox.height = oImg.height;
Run Code Online (Sandbox Code Playgroud)

当我在我的Spaceship构造函数中执行console.log(this)时,我可以看到proto属性设置为Spaceship而不是GameObject,如果我删除它们,则将其设置为GameObject.

如果我使用:

 Spaceship.prototype = GameObject.prototype;
Run Code Online (Sandbox Code Playgroud)

我没有更多的问题.这阻止我的原因是我有另一个带有add()方法的对象,它使用以下代码检查GameObject的对象是否有效:

 if(object instanceof GameObject)
Run Code Online (Sandbox Code Playgroud)

我不明白这两行可能会改变什么,以便继承在它们存在时被破坏而我不确定继承第二种方式是好的.有人可以告诉我这件事吗?:)

javascript inheritance

8
推荐指数
1
解决办法
1138
查看次数

超出最大调用堆栈大小 - 没有明显的递归

我花了大约12个小时查看这段代码,并摆弄它,试图找出有递归问题的地方,因为我得到了"超出最大调用堆栈大小"错误,并且没有找到它.比我聪明的人请帮助我!

到目前为止,我发现的只是当我创建对象时spot,一个circle对象,问题就消失了,但是当我把它变成'pip'时,我得到了这个堆栈溢出错误.我用一个friggin'显微镜看了一下pip类,但仍然不知道为什么会发生这种情况!

var canvas = document.getElementById('myCanvas');

//-------------------------------------------------------------------------------------
// Classes
//-------------------------------------------------------------------------------------
//=====================================================================================
//CLASS - point
function point(x,y){
    this.x = x;
    this.y = y;
}
//=====================================================================================
// CLASS - drawableItem
function drawableItem() {
    var size = 0;
    this.center = new point(0,0);
    this.lineWidth = 1;
    this.dependentDrawableItems = new Array();
}
//returns the size
drawableItem.prototype.getSize = function getSize(){
    return this.size;
}
// changes the size of this item and the relative size of all dependents
drawableItem.prototype.changeSize = function(newSize){
    var relativeItemSizes …
Run Code Online (Sandbox Code Playgroud)

javascript recursion inheritance callstack class

3
推荐指数
1
解决办法
1807
查看次数

标签 统计

javascript ×3

inheritance ×2

callstack ×1

class ×1

recursion ×1