// 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方法默許返回實例對象,1個類必須有該方法,沒有會被默許添加
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]
* 可以發現,兩次的打印1模1樣,我們可以理解為class實際上是構造函數的1個語法糖,只是為了讓JavaScript看起來更像1門面向對象的語言 *