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


当前回答

在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

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

其他回答

是的,你可以像这样在类声明中定义构造函数:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

使用原型:

function Box(color) // Constructor
{
    this.color = color;
}

Box.prototype.getColor = function()
{
    return this.color;
};

隐藏“color”(有点像私有成员变量):

function Box(col)
{
   var color = col;

   this.getColor = function()
   {
       return color;
   };
}

用法:

var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue

var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green

如果你使用微软开源的Typescript,他们就会这样做:-)

class BankAccount {
 balance: number;
 constructor(initially: number) {
 this.balance = initially;
 }
 deposit(credit: number) {
 this.balance += credit;
 return this.balance;
 }
}

Typescript让你“伪造”OO结构,这些结构被编译成javascript结构。如果你正在开始一个大型项目,它可以为你节省很多时间,而且它刚刚达到里程碑1.0版本。

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

上面的代码被“编译”为:

var BankAccount = (function () {
    function BankAccount(initially) {
        this.balance = initially;
    }
    BankAccount.prototype.deposit = function (credit) {
        this.balance += credit;
        return this.balance;
    };
    return BankAccount;
})();

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

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

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

在大多数情况下,在调用传递此信息的方法之前,必须以某种方式声明所需的属性。如果你不需要一开始就设置一个属性,你可以像这样在对象中调用一个方法。可能不是最漂亮的方法,但这仍然有效。

var objectA = {
    color: ''; 
    callColor : function(){
        console.log(this.color);
    }
    this.callColor(); 
}
var newObject = new objectA();