JavaScript原型继承

JavaScript原型可以实现类似于其他语言中的类继承


示例一:

// 父类型
function Person() {
	this.name = 'zs';
	this.age = 18;
	this.sex ='男';
}
// 子类型
function Student() {
	this.score = 100;
}
student.prototype = new Person();
Student.prototype.constructor = Student;

var s1 =new Student();
console.log(s1.constructor);
console.dir(s1);

缺点:这种继承无法对构造函数进行灵活传参。可以通过示例二进行改进。


示例二:

//借用构造函数//父类型
function Person( name, age, sex) {
	this.name = name;
	this.age = age;
	this.sex = sex;
}
// 子类型
function Student(name, age, sex, score) {
	Person.call(this, name, age, sex);
	this.score = score;
}
var s1 = new Student('zs', 18, '男', 100);
console.dir(s1);

call()改变函数中的this,直接调用函数
优点与不足:示例二通过构造函数实现了继承,这种继承方式可以灵活传参,但是无法继承构造函数中的原型对象中的内容。可以通过示例三进行改进。


示例三:

组合继承:借用构造函数 + 原型继承
function Person(name, age, sex) {
	this.name = name;
	this.age = age;
	this.sex = sex;
}
Person.prototype.sayHi = function() {
	console.log('大家好,我是'+ this.name);
}
function Student(name,age, sex,score) {
	// 借用构造函数
	Person.call(this, name, age, sex);
	this.score = score;
}
Student.prototype = Person.prototype;
Student.prototype.constructor = Student; // 构造函数原型对象中constructor必须指向构造函数,对象实例能够通过constructor查询实例的数据类型
var s1 = new Student( 'zs', 18, '男', 100);
console.dir(s1);

优点与不足:通过构造函数中的原型对象指向另一个构造函数的原型对象虽然能够实现对原型中方法的继承,但是这种继承方式会 改变“父”构造函数的原型对象 ,从而导致“父”构造函数原型对象所有实例对象__proto__的属性改变。可通过示例四进行改进。


示例四:

组合继承:借用构造函数 + 原型继承
function Person(name, age, sex) {
	this.name = name;
	this.age = age;
	this.sex = sex;
}
Person.prototype.sayHi = function() {
	console.log('大家好,我是'+ this.name);
}
function Student(name,age, sex,score) {
	// 借用构造函数
	Person.call(this, name, age, sex);
	this.score = score;
}
// -------------------------------
Student.prototype = new Person(); // 替换示例三中的 Student.prototype = Person.prototype;
// -------------------------------
Student.prototype.constructor = Student; // 构造函数原型对象中constructor必须指向构造函数,对象实例能够通过constructor查询实例的数据类型
var s1 = new Student('zs', 18, '男', 100);
console.dir(s1);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值