目錄:
概述:
初步理解:
1
2
3
4
|
function
name(obj){ alert(obj) //"uw3c" } name( "uw3c" ) |
1
2
3
4
5
|
function
name(obj){ alert(obj) //"uw3c" } var
test = new name( "uw3c" ) test(); |
1
2
3
4
5
|
function
uw3c(){ } var
test = new uw3c(); alert( typeof
uw3c); //function alert( typeof
test); //object |
1
2
3
4
5
6
|
function
name(){ alert(JSON.stringify(name.prototype)) //{},是個空對象 } name(); var
test = new name(); alert(JSON.stringify(test.prototype)) //undefined,不存在這個對象 |
什麼是prototype:
1
2
3
4
5
|
var
function { prototype:prototype{ constructor:constructor ==
function } } |
prototype的作用:
1
2
3
4
5
|
function
uw3c(){ } uw3c.prototype.name =
"a" ; var
test = new uw3c(); alert(test.name) //"a"; |
1
2
3
4
5
6
7
|
var
name = "js" ; function
uw3c(name){ alert( this .name); //"css" } uw3c.prototype.name =
"css" ; var
test = new uw3c(); test(); |
1
2
|
var
test={}; uw3c.call(test); |
第二步將該對象(test)內置的原型對象設置爲構造函數(就是uw3c)prototype 屬性引用的那個原型對象。
第三步就是將該對象(test)作爲this 參數調用構造函數(就是uw3c),完成成員設置等初始化工作。
其中第二步中出現了一個新名詞就是內置的原型對象,注意這個新名詞跟prototype對象不是一回事, 爲了區別我叫它inobj,inobj就指向了函數uw3c的prototype對象。在uw3c的prototype對象中出現的任何屬性或者函數都可以在test對象中直接使用,這個就是JS中的原型繼承了。
prototype是繼承還是克隆:
1
2
3
4
5
6
|
function
uw3c(){ } uw3c.prototype.name =
"b" ; var
test = new uw3c(); alert(JSON.stringify(test)); //{} alert(test.name); //"b" |
prototype的優點:
1
2
3
4
5
6
7
|
function
uw3c(name){ alert( "姓名:"
+ name + ",年齡:"
+ this .age +
",性別:" + this .sex); } uw3c.prototype.age = 15; uw3c.prototype.sex =
"man" ; var
test1 = new uw3c( "css" ); //姓名:css,年齡:15,性別:man var
test2 = new uw3c( "js" ); //姓名:js,年齡:15,性別:man |