JavaScript类/对象可以有构造函数吗?它们是如何产生的?
当前回答
只是为了提供一些变化。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
其他回答
这是一个构造函数:
function MyClass() {}
当你这样做时
var myObj = new MyClass();
MyClass被执行,并返回该类的一个新对象。
构造函数的意义是什么呢 财产吗?不知道它在哪里 可能有用,有什么想法吗?
构造函数属性的目的是提供某种方式来假装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
使用原型:
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
只是为了提供一些变化。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