9.1 Constructors
构造函数建立一个新的对象,一个没有属性且调用这个函数,传递新的对象作为 this 的值, 一个函数用new 去调用就是构造函数,构造函数及时为了初始化一个对象。在对象被使用前对其所有需要被赋值的属性赋值,我们可以建立自己的构造函数然后添加属性到this.
Code:
//Define the constructor.
//Note how it initializes the object referred to by "this".
function Rectangle(w,h){
this.width = w;
this.height = h;
// Note: no return statement here
}
//Invoke the constructor to create two Rectangle objects.
//We pass the width and height to the constructor
//so that it can initialize each new object appropriately.
var rect1 = new Rectangle(2,4);
var rect2 = new Rectangle(8.5, 11);
我们注意到了构造函数是怎样用它的参数去初始化一个 this所指向的对象的属性。Rectangle中的width 和 height就是这样被赋值的。这将意味着你所写的程序将依赖这样的行为并且一致的对待所有的Rectangle对象。因为每个构造函数都将定义很多的对象,所以在命名方面,我们用名词像Rectangle会比较直观,而不是init_rect这样。
那么看到这里,书中讲到构造函数一般是不会有返回值,他们会把被传递的对象初始化而作为this的值,不会返回任何东西。然而,一个构造函数是允许返回一个对象值,并且如果这么做,返回对象的值会作为表达式new的值,这种情况下,作为this的值的对象将会被丢弃。
Code:
function Sub(x,y) {
result = x – y;
return result;
}
Sub.prototype.toString = function() {
return "i’m a man!";
};
alert(new Sub(9,5));//i’m a man!
alert(result);//3
最好就是不要用返回值了- -!