Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DingWeizhe/39b8cf932e1ba4bcc46669bef80bda4b to your computer and use it in GitHub Desktop.
Save DingWeizhe/39b8cf932e1ba4bcc46669bef80bda4b to your computer and use it in GitHub Desktop.
function f(){}
// f 是一個 function
var o = {}
// o 是一個 object
function C(){
return this;
}
// C 是一個 Class
var o = new C();
// o 是一個 Class C 的 object
// 事實上 o = {} 意思就是 o = new Object();
function C(){
this.name = "XXX";
return this;
}
var o = new C();
// 這邊的name通常稱為Class的屬性
// 在每次實例化C的時候都會產生一個截然不同的name
function C(){
this.f = function(){ }
return this;
}
// 這邊的f稱為Class C的method
// 值得注意的事,在每次實例化C的時候都會產生一個截然不同的f
// 所以 new C().f !== new C().f
console.log(new C().f !== new C().f);
// 接下來是比較容易混淆的部分 prototype
function C(){
return this;
}
C.prototype.f2 = function(){}
// 這裡的f2稱為Class C的prototype method
// 值得注意的事,每個C的instance都共用這個f
// 所以 new C().f2 === new C().f2
console.log(new C().f2 === new C().f2);
// 此外你還可以這樣做!
function C(){
return this;
}
C.prototype.f3 = function(){}
var a = new C();
var b = new C();
b.f3 = function(){}
// 在method呼叫的時候會優先呼叫非prototype的method
console.log(a.f3 !== b.f3);
delete b.f3;
console.log(a.f3 === b.f3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment