竹笋

注册

 

发新话题 回复该主题

js交互开发高级基本内容第二十六节j [复制链接]

1#
好的白癜风医院在哪里 http://www.victroncapital.com/m/
好的白癜风医院在哪里 http://www.victroncapital.com/m/

一、js错误处理

1、如何进行错误处理

varo={};

o.func();  //这行代码会出错,因为调用了不存在的方法

console.log(test);  //前面的代码出错时,这行代码不会执行

varo={};

try{//在try中编写可能出现错误的代码

o.func();

console.log(a);//如果前面的代码出错,这行代码不会执行

}catch(e){//在catch中捕获错误,e表示错误对象

console.log(e);

}

console.log(b);//如果错误已经被处理,这行代码会执行

2、错误对象传递

3、抛出错误对象

try{

vare1=newError(错误信息);  //创建错误对象

throwe1;//抛出错误对象,也可以与上一行合并为:thrownewError(错误信息);

}catch(e){

console.log(e.message);  //输出结果:错误信息

console.log(e1===e);  //判断e1和e是否为同一个对象,输出结果:true

}

4、错误类型

案例演示:语法错误

try{

varo={;};  //语法错误

}catch(e){

console.log(e.message);

}

二、继承

继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的属性和方法,或子类从父类继承方法,使得子类具有父类相同的行为。

1、借用构造函数继承父类属性

call()方法:将父类的this指向子类的this,这样就可以实现子类继承父类的属性。

functionFather(uname,age){//Father构造函数是父类

this.uname=uname;

this.age=age;

}

functionSon(uname,age,score){//Son构造函数是子类

Father.call(this,uname,age);//子类继承父类的属性

this.score=score;//子类可以拥有自己的特有属性

}

varson=newSon(张三,18,);

console.log(son);  //输出结果:Son{uname:"张三",age:18,score:}

2、利用原型对象继承父类方法

原型对象继承父类方法:将父类的实例对象作为子类的原型对象来使用

functionFather(){}

Father.prototype.money=function(){console.log(000);};

functionSon(){}

Son.prototype=newFather();//将父类的实例对象作为子类的原型对象

Son.prototype.constructor=Son;//将原型对象的constructor属性指向子类

newSon().money();//调用父类money()方法,输出结果:000

Son.prototype.exam=function(){};//为子类增加exam()方法

console.log(Father.prototype.exam);//子类不影响父类,输出结果:undefined

原型链示意图:

class语法的本质:类和构造函数的使用非常相似,可以互相替代。

classPerson{}

console.log(Person.prototype);//类也有原型对象

Person.prototype.money=function(){//类也可以增加方法

console.log(000);

};

newPerson().money();//输出结果:000

分享 转发
TOP
发新话题 回复该主题