gpt4 book ai didi

javascript - 通过在一条语句中合并函数和对象来创建类。在 javascript 中定义类的替代方法

转载 作者:行者123 更新时间:2023-11-29 19:45:36 28 4
gpt4 key购买 nike

什么激怒我:

PersonClass = function(){
console.log("Person created!")
}
PersonClass.prototype = {name:"John Doe"}

我们必须至少输入类名“PersonClass”两次,以声明具有属性的类。我得到了什么:

with(PersonClass = function(){
console.log("Person created!")
})
{
prototype = {name:"John Doe"}
}

它很丑,但是!我们不必每次要定义类结构时都过多地写PersonClass。我的问题是:您是否知道在 javascript 中声明类的其他替代方法,可能是古怪的方法?

最佳答案

尝试 http://classy.pocoo.org/ ,你可以用它来定义类:

var Animal = Class.$extend({
__init__ : function(name, age) {
this.name = name;
this.age = age;
this.health = 100;
},

die : function() {
this.health = 0;
},

eat : function(what) {
this.health += 5;
}
});

关于javascript - 通过在一条语句中合并函数和对象来创建类。在 javascript 中定义类的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19977298/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com