JavaScript语言传统方法是通过构造函数定义并生成新对象。例:
function Add (a, b) {
this.a = a;
this.b = b;
}
Add.prototype.toString = function () {
return this.a + this.b;
}
var add = new Add(5, 8)
而在ES6中,引入了Class这个概念来作为对象的模板。而class只是一个语法糖写法,还是基于ES5封装而来的。上面的例子用class来改写如下:
// 定义类
class Add {
constructor (a, b) {
this.a = a;
this.b = b;
}
toString () {
return this.a + this.b;
}
}
注:方法之间不需要加逗号,否则会报错。
从中可见一个constructor方法,这便是构造方法。另外,关键字this则代表实例对象。
// Object.assign(类原型,{方法列表})
Object.assign(Add.prototype, {
toString () {},
toValue () {}
})
class Add {
constructor (a, b) {
// ...
}
toString () {
// ...
}
}
Object.keys(Add.prototype); // []
Object.getOwnPropertyNames(Add.prototype); // ["constructor", "toString"]
const methodName = 'getValue';
class Add {
constructor (a, b) {
// ...
}
[methodName] () {
// ...
}
}
类和模版的内部默认使用严格模式,所以无需使用use strict指定运行模式。只要将代码卸载类或者模块之中,就只有严格模式可用。ES6已经把整个语言都升级到了严格模式下。
constructor方法是类的默认方法,通过new命令生成对象实例时自动调用该方法。如果类中没有显式定义,则会默认添加一个空的constructor方法。例:
class Add {
}
// 等同于
class Add {
constructor () {}
}
上面代码中定义了一个空的类Add,JavaScript引擎会自动给它添加一个空的constructor方法。除此之外,还需注意的是:
实例的属性除非是显式定义在this对象上,否则都是定义在了Class上。
class Add {
constructor (a, b) {
this.a = a;
this.b = b;
}
toString () {
return this.a + this.b;
}
}
var add = new Add(5, 8);
add.toString(); // 13
add.hasOwnProperty('a'); // true
add.hasOwnProperty('b'); // true
add.hasOwnProperty('toString'); // false
add.__proto__.hasOwnProperty('toString'); // true
从上面代码中,a和b都是实例对象Add自身的属性,因为定义在this变量上,所以执行hasOwnProperty方法返回true;而toString是原型对象的属性,因为定义在Add上,所以hasOwnProperty方法返回的事false。另外,类的所有实例共享一个原型对象;可以通过实例的proto属性为类来添加方法。
除上述所说之外,类同样有很多有意思的属性或者方法,此处放上一些,以供参考。
参考:ECMAScript 6 入门 - 阮一峰
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有