网站搜索

JavaScript - Google 应用脚本中的子类和继承


有人有在 Google Apps Script 中编写和子类化对象的任何模式吗?

我尝试过使用 ParentClass.call(this, args) 来定义子类,并且将父类方法放在父类的原始定义中,同时赋给 ParentClass.prototype。但是虽然这段代码可以通过单元测试,在 Google Apps Script 中使用时却会失败。

答案#1

这是关于类继承的(但 JavaScript 并没有真正的“类”)。你可以使用 Prototype.js 或 mootool.js,或者像这样做?

function Human () {
    this.init.apply ( this, arguments );
}
Human.prototype = {
    init: function () {
        var optns = arguments[0] || {};
        this.age = optns.age || 0;
        this.name = optns.name || "nameless";
    },
    getName : function () {
        return this.name;
    },
    getAge : function () {
        return this.age;
    }
}

function Man () {
    this.init.apply ( this, arguments );
}
Man.prototype = {
    init : function () {
        Human.prototype.init.apply (this, arguments);
        this.sex = "man";
    },
    getName : Human.prototype.getName,
    getAge : Human.prototype.getAge,
    getSex : function () {
        return this.sex;
    }
}
function Woman () {
    this.init.apply ( this, arguments );
}
Woman.prototype = {
    init : function () {
        Human.prototype.init.apply (this, arguments);
        this.sex = "woman";
    },
    getName : Human.prototype.getName,
    getAge : Human.prototype.getAge,
    getSex : Man.prototype.getSex
}

var human = new Human({age:60,name:"Tom Tomas"}),
    man1 = new Man({age:30,name:"Wood Tomas"}),
    woman1 = new Woman({age:19,name:"Mary Tomas"});

console.log( human.getName() );
console.log( man1.getName() );
console.log( woman1.getName() );

console.log( human.getAge() );
console.log( man1.getAge() );
console.log( woman1.getAge() );

console.log( human.getSex && human.getSex() );
console.log( man1.getSex() );
console.log( woman1.getSex() );

或者你可以使用 jQuery 的 $.extend 来做这个。希望能帮到你!

答案#2

错误:ReferenceError: <class> 未定义

如果你的代码是正确的,但在 Google Script 平台上仍然无法工作(出现上述异常),试着对文件进行排序。是的,真的,排序它。

但即使在排序之后,如果仍然抛出 ‘ReferenceError: 未定义’ 错误,尝试手动排序文件。确保未定义的类文件首先被执行,可以通过重命名文件来实现。

001_Animal.gs < 未定义的类
002_Rabbit.gs
003_Main.gs

可以在这里找到关于此问题的更多信息。

我有一个没有代码错误的脚本,但它不起作用。还有,我用了@Valentin的代码,也不起作用。我所需要做的只是排序。之后,它就可以工作了。

我在这里使用 @Valentin 的代码。