JS实现继承

ES5实现

方式一:子类原型指向父类实例;

缺点:
                    1.无法向父类传参
                    2.想在子类原型上添加方法必须在new Person之后
                    3.父类原型上所有属性被共享


				function Person(name, age) {
					this.name = name;
					this.age = age;
				}
				Person.prototype.sex = "男"

				function Student(stuNo) {
					this.stuNo = stuNo;
				}
				Student.prototype = new Person();
				let stu = new Student("2016190319");
				console.log(stu.stuNo);
				console.log(stu.sex);
				console.log(stu.name)

方式二:构造函数+子类原型指向父类实例

 

function Person(options) {
				this.name = options.name;
				this.age = options.age;
			}
			Person.prototype.sex = "男"

			function Student(options) {
				Person.call(this, options)
				this.stuNo = options.stuNo;
			}
			Student.prototype = Object.create(Person.prototype);
			Student.prototype.constructor = Student;
			Student.prototype.say = function() {
				console.log("hello")
			}
			let stu = new Student({
				name: "小刘",
				age: "18",
				stuNo: "2016190319"
			});
			console.log(stu.stuNo);
			console.log(stu.sex);
			console.log(stu.name);
			console.log(stu.say());

ES6 class实现继承 语法糖

class Person {
				// sex:"name"
				constructor(options) {
					this.name = options.name;
					this.age = options.age;
				}
				get sex() {
					return "男"
				}

			}
			class Student extends Person {
				constructor(options) {
					super(options);
					this.stuNo = options.stuNo;
				}
				say() {
					console.log("hello")
				}
			}
			let stu = new Student({
				name: "小刘",
				age: "18",
				stuNo: "2016190319"
			});
			console.log(stu.stuNo);
			console.log(stu.sex);
			console.log(stu.name);
			console.log(stu.say());

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值