Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过在一条语句中合并函数和对象来创建类。用javascript定义类的另一种方法_Javascript - Fatal编程技术网

通过在一条语句中合并函数和对象来创建类。用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);
演示: