10.继承方式一

2019-06-06  本文已影响0人  Fl_来看看
Student.prototype = new Person();
        Student.prototype.constructor = Student;
        修改了原型对象,记得构造函数也得修改回
function Person() {
            this.name = null;
            this.age = 0;
            this.say = function () {
                console.log(this.name, this.age);
            }
        }
        let per = new Person();
        per.name = "lnj";
        per.age = 34;
        per.say();

        // 在企业开发中如果构造函数和构造函数之间的关系是is a关系, 
        //那么就可以使用继承来优化代码, 来减少代码的冗余度
        // 学生 is a 人 , 学生是一个人
        
        //继承不能乱用,即使有共同的属性也不能用,
        //比如狗有姓名,但狗不是人,得学生 is a 人 , 学生是一个人~!
        function Student() {
            this.score = 0;
            this.study = function () {
                console.log("day day up");
            }
        }
        Student.prototype = new Person();
        Student.prototype.constructor = Student;

        let stu = new Student();
        stu.name = "zs";
        stu.age = 18;
        stu.score = 99;
        stu.say();
        stu.study();

这种方式有弊端:无法在new Student();设置name,age,say。

上一篇 下一篇

猜你喜欢

热点阅读