生成实例对象的传统方法是通过构造函数:
function
Point
(
x
,
y
)
{
this
.
x
=
x
;
this
.
y
=
y
;
}
Point
.
prototype
.
toString
=
function
(
)
{
return
'('
+
this
.
x
+
', '
+
this
.
y
+
')'
;
}
;
//定义类
class Point
{
constructor
(
x
,
y
)
{
this
.
x
=
x
;
this
.
y
=
y
;
}
toString
(
)
{
return
'('
+
this
.
x
+
', '
+
this
.
y
+
')'
;
}
}
类的数据类型就是函数,类本身就指向构造函数。
typeof Point // "function"
Point === Point.prototype.constructor // true
调用
let point =new Point(3,4)
point.toString()
类的所有方法都定义在类的prototype属性上面。
在类的实例上面调用方法,其实就是调用原型上的方法。
class B {}
let b = new B();
b.constructor === B.prototype.constructor // true
由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。
class Point {
constructor(){ // ... }
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});
prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。
Point.prototype.constructor === Point // true
类的属性名,可以采用表达式。
let methodName = 'getArea';
class Square {
constructor(length) { // ... } [methodName]() { // ... }
}
与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。
//定义类class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() { return '(' + this.x + ', ' + this.y + ')'; }}
var point = new Point(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
与 ES5 一样,类的所有实例共享一个原型对象。
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__ === p2.__proto__
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__.printName = function () { return 'Oops' };
p1.printName() // "Oops"
p2.printName() // "Oops"
var p3 = new Point(4,2);
p3.printName() // "Oops"
与函数一样,类也可以使用表达式的形式定义。
const MyClass = class Me {
getClassName() { return Me.name; }
};
上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是MyClass而不是Me,Me只在 Class 的内部代码可用,指代当前类。
let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined
上面代码表示,Me只在 Class 内部有定义。
如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。
const MyClass = class { /* ... */ };
采用 Class 表达式,可以写出立即执行的 Class。
let person = new class {
constructor(name) {
this.name = name;
}
sayName() { console.log(this.name); }}('张三');
person.sayName(); // "张三"
上面代码中,person是一个立即执行的类的实例。
私有方法
class Widget
{
foo
(
baz
)
{
bar
.
call
(
this
,
baz
)
;
}
// ...
}
function
bar
(
baz
)
{
return
this
.
snaf
=
baz
;
}