日期:2014-05-16  浏览次数:20474 次

javascript面向对象技术基础(五)(转载)

原文:javascript面向对象技术基础(五)

类变量/类方法/实例变量/实例方法
先补充一下以前写过的方法:
在javascript中,所有的方法都有一个call方法和apply方法.这两个方法可以模拟对象调用方法.它的第一个参数是对象,后面的
参数表示对象调用这个方法时的参数(ECMAScript specifies two methods that are defined for all functions, call()
and apply(). These methods allow you to invoke a function as if it were a method of some other object. The first
argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes
the value of the this keyword within the body of the function. Any remaining arguments to call() are the values
that are passed to the function that is invoked).比如我们定义了一个方法f(),然后调用下面的语句:
f.call(o, 1, 2);
作用就相当于
o.m = f;
o.m(1,2);
delete o.m;
举个例子:

Js代码
  1. function ?Person(name,age)?{?? //定义方法 ??
  2. ????this .name?=?name;??
  3. ????this .age?=?age;??
  4. }??
  5. var ?o?=? new ?Object();??? //空对象 ??
  6. alert(o.name?+?"_" ?+?o.age);? //undefined_undefined ??
  7. ??
  8. Person.call(o,"sdcyst" ,18);? //相当于调用:o.Person("sdcyst",18) ??
  9. alert(o.name?+?"_" ?+?o.age);? //sdcyst_18 ??
  10. ??
  11. Person.apply(o,["name" ,89]); //apply方法作用同call,不同之处在于传递参数的形式是用数组来传递 ??
  12. alert(o.name?+?"_" ?+?o.age);? //name_89 ??
function Person(name,age) {  //定义方法
    this.name = name;
    this.age = age;
}
var o = new Object();   //空对象
alert(o.name + "_" + o.age); //undefined_undefined

Person.call(o,"sdcyst",18); //相当于调用:o.Person("sdcyst",18)
alert(o.name + "_" + o.age); //sdcyst_18

Person.apply(o,["name",89]);//apply方法作用同call,不同之处在于传递参数的形式是用数组来传递
alert(o.name + "_" + o.age); //name_89

?---------------------------------

实例变量和实例方法都是通过实例对象加"."操作符然后跟上属性名或方法名来访问的,但是我们也可以为类来设置方法或变量,
这样就可以直接用类名加"."操作符然后跟上属性名或方法名来访问.定义类属性和类方法很简单:

Js代码
  1. Person.counter?=?0;??? //定义类变量,创建的Person实例的个数 ??
  2. function ?Person(name,age)?{??
  3. ????this .name?=?name;??
  4. ????this .age?=?age;??
  5. ????Person.counter++;?//没创建一个实例,类变量counter加1 ??
  6. };??
  7. ??
  8. Person.whoIsOlder?=?function (p1,p2)?{? //类方法,判断谁的年龄较大 ??
  9. ????if (p1.age?>?p2.age)?{??
  10. ????????return ?p1;??
  11. ????}?else ?{??