JS--自定義物件的幾種方法
Sam Stephenson寫的Prototype JavaScript framework,
最基本的:建構函式&&實名方法[code]
}
function sum(a, b){return a + b;}
//新增方法
MyObject.prototype.sum = sum;
var b = new MyObject();2 Z |: |. S w* F. m5 @
alert(b.sum(3, 4));
建構函式&&匿名方法 . V- /. S7 i* _2 C& K& s" ?6 M
//定義MyObject物件
function MyObject() {}
//新增方法
MyObject.prototype.sum = function(a, b){return a + b};
var b = new MyObject();. v3 ~& s( N' d
alert(b.sum(3, 4));
建構函式&&匿名方法(2) 5 d1 h$ Q5 d) d" R. S9 y' /. u
D
//定義MyObject物件/ s. _* B# V+ }
function MyObject() {}
//新增方法
MyObject.prototype = {sum:function(a, b){return a + b;}};
var b = new MyObject();
alert(b.sum(3, 4));
建構函式&&匿名方法(3) - z! u9 /7 ^5 R* E ~
//定義MyObject物件
function MyObject()
{
this.sum = function(a, b){return a + b};& Y5 [/ Q D' A7 d* D) h: Y& W
}9 ?$ s3 `4 f' L6 ?- j
var b = new MyObject();
alert(b.sum(3, 4));
$ U' l$ U. C. y5 _3 a9 S
匿名物件(屬性)
var a = 22;) x" d8 X' |0 F: Z7 /; t
//b是物件,該物件有一個屬性c,它是由變數a賦值給它的
var b = {c:a};# M# F0 a; V% F( `9 e
alert(b.c); ]$ X7 ]2 s/ t' t. p
匿名物件(方法) ) p( /7 B! N6 s2 h! f0 S/ ]
" a: k2 o" W' N
var b = {sum:function(a, b){return a + b;}};, /: c. }3 u6 j
alert(b.sum(3, 4));