js实现继承的三种方式

js实现继承的三种方式

构造继承

构造继承,改变this指向
Person.call(this, x, y)

//构造继承 call()
    //目的:让学生去继承人的属性和方法(构造函数的属性和方法 原型上的属性和方法)
    //创建构造函数Person
    function Person(name, age) {
        this.name = name
        this.age = age
        this.eat = function () {
            console.log(this.name + '喜欢吃');
        }
    }
    //设置原型上的属性和方法
    Person.prototype.sex = '男'
    Person.prototype.sleep = function () {
        console.log('喜欢睡觉');
    }
    //创建构造函数Student
    function Student(code, x, y) {
        this.code = code
        this.play = function () {
            console.log(this.name + '玩');
        }
        //构造继承,改变this指向
        Person.call(this, x, y)
    }
    //构造继承不能拿到人原型上的属性和方法
    Student.prototype = new Person()
    Student.prototype.height = 200
    Student.prototype.love = function () {
        console.log('喜欢搞对象');
    }
    //实例化Student
    var stu = new Student(100, '小明', 18);
    console.log(stu);
    //学生构造函数的属性和方法
    console.log(stu.code);
    stu.play()
    //学生原型上的属性和方法
    console.log(stu.height);
    stu.love()
    //人构造函数的属性和方法
    console.log(stu.name);
    stu.eat()
    //人原型上的属性和方法
    console.log(stu.sex);
    stu.sleep()

原型继承

让学生继承人的属性和方法
Student.prototype = new Person(‘小明’, 20);

//创建构造函数Person
function Person(name, age) {
        this.name = name
        this.age = age
        this.eat = function () {
            console.log('喜欢吃');
        }
    }
    //原型上的属性和方法
    Person.prototype.sex = '男'
    Person.prototype.sleep = function () {
        console.log('喜欢睡觉');
    }
    //创建构造函数Student
    function Student(code) {
        this.code = code
        this.play = function () {
            console.log('玩');
        }
    }
   //让学生继承人的属性和方法
    Student.prototype = new Person('小明', 20);
	//设置原型对象上的属性和方法
    Student.prototype.height = 200
    Student.prototype.love = function () {
        console.log(this.name + '喜欢搞对象');
    }
    //实例化Student对象
    var stu = new Student(100)
   	//调用
    stu.love()
    stu.play()
    console.log(stu.age);
    stu.eat()
    console.log(stu.sex);
    stu.sleep()

拷贝继承

for in遍历
for (x in p) {
stu[x] = p[x]
}

 var stu = new Student(100);
    var p = new Person('小明', 18)
    for (x in p) {
        stu[x] = p[x]
    }
    console.log(stu);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值