JavaScript类/对象可以有构造函数吗?它们是如何产生的?


当前回答

在使用上面Blixt的伟大模板时,我发现它不能很好地使用多级继承(MyGrandChildClass扩展MyChildClass扩展MyClass)——它循环调用第一个父类的构造函数。这里有一个简单的解决方法-如果你需要多级继承,而不是使用this.constructor.super。调用(这,姓氏);使用chainSuper()。调用(这,姓氏);链函数定义如下:

function chainSuper(cls) {
  if (cls.__depth == undefined) cls.__depth = 1; else cls.__depth++;
  var depth = cls.__depth;
  var sup = cls.constructor.super;
  while (depth > 1) {
    if (sup.super != undefined) sup = sup.super;
    depth--;
  }
  return sup;
}

其他回答

只是为了提供一些变化。ds。Oop是一种在javascript中使用构造函数声明类的好方法。它支持所有可能的继承类型(包括一种甚至c#都不支持的类型)以及很好的接口。

var Color = ds.make.class({
    type: 'Color',
    constructor: function (r,g,b) { 
        this.r = r;                     /* now r,g, and b are available to   */
        this.g = g;                     /* other methods in the Color class  */
        this.b = b;                     
    }
});
var red = new Color(255,0,0);   // using the new keyword to instantiate the class

构造函数的意义是什么呢 财产吗?不知道它在哪里 可能有用,有什么想法吗?

构造函数属性的目的是提供某种方式来假装JavaScript有类。你不能做的一件事是在创建对象后更改对象的构造函数。它是复杂的。

几年前我写了一篇相当全面的文章:http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

这里我们需要注意一点,它是一种无类语言,但是我们可以通过使用java script中的函数来实现。实现这一点最常见的方法是我们需要在java脚本中创建一个函数,并使用new关键字来创建一个对象,并使用此关键字来定义属性和方法。下面是示例。

// Function constructor

   var calculator=function(num1 ,num2){
   this.name="This is function constructor";
   this.mulFunc=function(){
      return num1*num2
   };

};

var objCal=new calculator(10,10);// This is a constructor in java script
alert(objCal.mulFunc());// method call
alert(objCal.name);// property call

//Constructors With Prototypes

var calculator=function(){
   this.name="Constructors With Prototypes";
};

calculator.prototype.mulFunc=function(num1 ,num2){
 return num1*num2;
};
var objCal=new calculator();// This is a constructor in java script
alert(objCal.mulFunc(10,10));// method call
alert(objCal.name); // property call

在JavaScript中调用类型定义了函数的行为:

直接调用 对象上的方法调用obj.func() 构造函数调用new func() 间接调用func.call()或func.apply()


该函数在使用new操作符调用时作为构造函数调用:

function Cat(name) {
   this.name = name;
}
Cat.prototype.getName = function() {
   return this.name;
}

var myCat = new Cat('Sweet'); // Cat function invoked as a constructor

JavaScript中的任何实例或原型对象都有一个属性构造函数,它引用构造函数。

Cat.prototype.constructor === Cat // => true
myCat.constructor         === Cat // => true

查看这篇关于构造函数属性的文章。

我想我会发布我用javascript闭包做的事情,因为还没有人使用闭包。

var user = function(id) {
  // private properties & methods goes here.
  var someValue;
  function doSomething(data) {
    someValue = data;
  };

  // constructor goes here.
  if (!id) return null;

  // public properties & methods goes here.
  return {
    id: id,
    method: function(params) {
      doSomething(params);
    }
  };
};

欢迎对此解决方案提出意见和建议。:)