Chapter 9 JavaScript Classes,Constructors,and Prototypes - - - 9.1 Constructors

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

最好就是不要用返回值了- -!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值