使用dojo 1.8声明创建类

时间:2012-09-30 13:13:28

标签: javascript class dojo

我正在使用dojo 1.8作为javascript库。 我正在尝试为我的项目创建一个小型Vector类。

我已经创建了一个克隆矢量对象的函数克隆。这是我的班级“td / Vector”

define([
    'dojo/_base/declare',
    'td/Vector'
], function(declare, Vector) {
return declare(null, {

    x: null,
    y: null,

    constructor: function(x, y) {
        this.x = x;
        this.y = y;
    },

    clone: function() {
        return new Vector(this.x, this.y);
    },

    length: function() {
        return Math.sqrt((this.x * this.x) + (this.y * this.y));
    },

    normalize: function() {
        var length = this.length();
        this.x = this.x / length;
        this.y = this.y / length;
    },

    distance: function(target) {
        return new Vector(target.x - this.x, target.y - this.y);
    }
});
});

现在我的问题:

变量“Vector”是一个空对象。

那我怎么能这样做呢。 JavaScript中是否存在类似PHP中的“self”?在类本身中创建一个新的self实例的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

Vector变量是td/Vector模块的返回值,即td/Vector.js文件,而不是上面declare的类,这应该是它为空的原因对象

引用课程本身:

define(["dojo/_base/declare"], function(declare) {

    var Vector = declare(null, {    

        constructor: function(x, y) {
            this.x = x;
            this.y = y;
        },

        clone: function() {
            return new Vector(this.x, this.y);
        }
    });

    return Vector;

});

在jsFiddle中查看它:http://jsfiddle.net/phusick/QYBdv/

相关问题