通过在一条语句中合并函数和对象来创建类。用javascript定义类的另一种方法
让我恼火的是什么:通过在一条语句中合并函数和对象来创建类。用javascript定义类的另一种方法,javascript,Javascript,让我恼火的是什么: PersonClass = function(){ console.log("Person created!") } PersonClass.prototype = {name:"John Doe"} 我们必须将类名“PersonClass”至少放置两次,才能用属性声明类。 我想说的是: with(PersonClass = function(){ console.log("Person created!") }) { prototype = {na
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声明类的其他替代方法吗?可能有些古怪的方法吗?试试,使用它您可以定义如下类别:
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;
}
});
你也可以这样做:
(PersonClass = function(){
console.log("Person created!")
}).prototype = {name:"John Doe"}
但这不是特别好的风格。通常,声明对象的方式取决于您的框架
$。扩展
,类。创建
等。您可以编写一个函数,为自己创建类,而不是将与一起使用,并且必须注意它的所有缺陷:
function createClass(options) {
options.constructor.prototype = options.prototype;
return options.constructor;
}
PersonClass = createClass({
constructor: function(){
console.log("Person created!");
},
prototype : {name:"John Doe"}
});
var p = new PersonClass();
console.log(p.name);
另一个有趣的选择是:
Function.prototype.addPrototype = function(prototype) {
this.prototype = prototype;
return this;
}
PersonClass2 = function() {
console.log("Person created!");
}.addPrototype({ name:"John Doe" });
var p2 = new PersonClass2();
console.log(p2.name);
演示: