javascript 对象继承

继承的定义:创建一个或多个类的专门版本类的方式称为继承。

javascript只支持单继承,创建的专门版本的类通常叫做子类,另外的类称为父类。在现代浏览器中你可以使用Object.create实现继承。

举个例子,定义一个父类Person类,然后定义Student类作为Person类的子类,之后重新定义sayHello()方法并添加了sayGoodbye()方法。

//定义Person构造器
function Person( firstName){
this. firstName= firstName;
}

//在Person.prototype中加入方法
Person. prototype. walk= function(){
alert( "I am walking!");
}

Person. prototype. sayHello= function(){
alert( "Hello, I'm "+ this. firstName);
}

//定义Student构造器
function Student( firstName, subject){
//调用父类构造器,确保“this”在调用过程中设置正确
Person. call( this, firstName);

//初始化类Student类的特有属性
this. subject= subject;
}

//建立一个由Person.prototype继承而来的Student.prototype
//注意:常见的错误是使用“new Person()” 来建立Student.prototype
//这样做的错误之处有很多,最重要的一点是我们在实例化时
//不能赋予Person类任何的firstName参数
//调用Person的正确位置如下,我们从Student中来调用它
Student. prototype= Object. create( Person. prototype);
//设置“constructor”属性指向Student
Student. prototype. constructor= Student;

//更换SayHello方法
Student. prototype. sayHello= function(){
console. log( "Hello,I'm "+ this. firstName+ ", I'm studying "+ this. subject);
}

//加入sayGoodbye方法
Student. prototype. sayGoodBye= function(){
console. log( "Goodbye!")
}

//测试实例
var student1= new Student( "John smith", "chinese");
student1. sayHello(); //Hello,I'm John smith, I'm studing chinese
student1. walk(); //I am walking
student1. sayGoodBye(); //Goodbye

//check that instanceof works correctly
console. log( student1 instanceof Person); // true
console. log( student1 instanceof Student); // true

运行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值