2

让我恼火的是:

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中声明一个类的其他替代方法吗?

4

3 回答 3

1

尝试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;
}
});
于 2013-11-14T12:16:35.483 回答
1

你也可以这样做:

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

但这不是特别好的风格。通常,您声明对象的方式取决于您的框架。$.extendClass.create

于 2013-11-14T12:20:56.170 回答
1

您可以编写一个为您创建类的函数,而不是使用with并且不必注意它的所有陷阱:

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);

演示:http: //jsbin.com/AJItuJA/1/edit

于 2013-11-14T12:23:11.550 回答