JavaScript Class模拟基础

Simulating Classes in JavaScript

目前,用js来模拟class是一件非常麻烦的事情,多少有点不优雅。
但是未来的JS肯定会支持class,那么这个语言就是基于class和Prototype的混合继承?到时候会不会越来越混乱呢?笑……


Instance Properties
实例属性
[quote]By default, any object property in JavaScript is an instance property. [/quote]
对象的属性默认状态就是“实例属性”

Instance Methods
实例方法
[quote]In JavaScript, an instance method for a class is defined by setting a property in the constructor's prototype object to a function value.

In Java and C++, the scope of instance methods includes the this object.

return width * height;
In JavaScript, however, you've seen that you must explicitly specify the this keyword for these properties:

return this.width * this.height;

If you find it awkward to have to prefix each instance field with this, you can use the with statement (covered in Section 6.18.) in each of your methods.

Rectangle.prototype.area = function( ) {
with(this) {
return width*height;
}
}

[/quote]
在对象的Prototype对象中顶一个包含方法的属性就可以实现“对象的实例方法”

再诸如Java、C++之类的语言中,实例方法的作用域中包含当前对象,而JavaScript不包括。
所以你要在实例方法中引用实例属性的话就要时刻加上this:

return this.width * this.height;


Class Properties
类属性,也就是在JAVA中由static修饰的变量,是通过定义构造函数对象的内置属性来实现的。
Rectangle.UNIT = new Rectangle(1,1);


Class Methods
类方法,与类属性的实现方式一致

Private Members
私有成员
[quote]JavaScript can simulate this using closures (an advanced topic, covered in Section 8.8.), but to do so, the accessor methods must be stored on each object instance; they cannot be inherited from the prototype object.[/quote]

实现私有变量就是重头戏了,要用到闭包,而且必须和JAVA中一样,通过getter和setter访问他们。在JS中getter和setter必须保存到每个对象的实例中,是不能继承的(否则属性值不就乱了么)。

function ImmutableRectangle(w, h) {
// This constructor does not store the width and height properties
// in the object it initializes. Instead, it simply defines
// accessor methods in the object. These methods are closures and
// the width and height values are captured in their scope chains.
this.getWidth = function( ) { return w; }
this.getHeight = function( ) { return h; }
}

// Note that the class can have regular methods in the prototype object.
ImmutableRectangle.prototype.area = function( ) {
return this.getWidth( ) * this.getHeight( );
};



上例中,getter是在构造函数中定义的,所以确保了它的唯一性。闭包使外界无法通过任何手段来访问原来的定义的“私有变量”。例子中,构造函数的引用已经消失,垃圾回收会回收它,而定义的嵌套函数getWidth和getHeight却保留对原构造函数的引用(意味着这些返回的函数的作用链域中包含原构造函数的活动对象,自然可以访问到其参数值,w和h)

而且如果你只定义了getter,和java中一样,那么这个私有变量是只读的了,所以是ImmutableRectangle。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值