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

js学习笔记2

JS继承

1.对象冒充

function ClassA(sColor){
?? ?this.color = sColor;
?? ?this.sayColor = function(){
?? ?}
?}

function ClassB(sColor){

?? 相当于重新定义了在ClassA中的方法
?? ?this.newMethod = ClassA;
?? ?this.newMethod(sColor);
??? delete this.newMethod;
}

?

2.call及apply

? function test(t1,t2){

?????? alert(this.color);

? }

?

? var obj = new Object;

? obj.color = "red";

?

? test.call(obj,t1,t2);

? test.apply(obj,new Array(t1,t2));

?

function ClassA(sColor){
?? ?this.color = sColor;
?? ?this.sayColor = function(){
?? ?}
?}

function ClassB(sColor){

?? //相当于重新定义了在ClassA中的方法
?? // this.newMethod = ClassA;
??? //this.newMethod(sColor);
??? //delete this.newMethod;

??? //改为

??? ClassA.call(this,sColor);或ClassA.call(this,new Array(sColor));
}

?

3.原型链

? function ClassA(){

? }

? ClassA.prototype.color = "red";

? ClassA.prototype.sayColor(){

?????? alert(this.color);

?}

?

? function ClassB(){

? }

?

?? ClassB.prototype = new ClassA();

?? ClassB.prototype.otherMethod //Or otherField

?

4.混合方式

?? function ClassA(sColor){

????? this.color = sColor;

?? }

?? ClassA.prototype.sayColor(){

?????? alert(this.color);

? }

?

?? function ClassB(sColor){

????? ClassA.call(this,sColor);

?? }

?? ClassB.prototype = new ClassA();

?? ClassB.prototype.otherMethod //Or otherField

?

浏览器中的JS

对于不支持JS的浏览器的解决方法

<script ><!--

//-->

及<noscript>

?