ES6与ES5对比—–’类’
// ES5
function Application() {
this.a = 123;
this.b = 456;
this.foo = function() {
return 135;
}
}
var pro = Application.prototype;
pro.bar = function() {
return 246;
}
var app = new Application();
console.dir(typeof Application); // => 'function'
console.dir(Application); // => [Function: Application]
console.dir(app); // => {a:123, b: 456, foo: [function]}
console.dir(typeof app); // => 'object'
console.dir(app.bar()); // => 246
// ES6
class Application {
// constructor方法默认返回实例对象,一个类必须有该方法,没有会被默认添加
constructor() {
this.a = 123; // => this指代新的实例对象,即new的对象
this.b = 456;
this.foo = function() {
return 135;
}
}
bar() {
return 246;
}
}
let app = new Application();
console.dir(typeof Application); // => 'function'
console.dir(Application); // => [Function: Application]
console.dir(app); // => {a:123, b: 456, foo: [function]}
console.dir(typeof app); // => 'object'
console.dir(app.bar()); // => 246
console.dir(app.constructor); // => [Function: Application]
* 可以发现,两次的打印一模一样,我们可以理解为class实际上是构造函数的一个语法糖,只是为了让JavaScript看起来更像一门面向对象的语言 *