Javascript 面向对象-继承

JavaScript虽然不是面向对象的语言,但是我们通过构造可以让其支持面向对象,从而实现继承、重写等面向对象的特性。具体代码如下:

//创建类Person
function Person(age,name){
    this.age=age;
    this.name=name;
    
    this.sayHello=function(){
        console.log("大人大家好,我叫"+this.name+",今年"+this.age+"岁");
    }
}

//创建类Student,增加属性学号
function Student(age,name,stuNo){
    this.stuNo=stuNo;
    Person.call(this,age,name);//继承Person类,注意区分call和apply
    
    //重写sayHello
    this.sayHello=function(){
        console.log("学生大家好,我叫"+this.name+",今年"+this.age+"岁,学号是:"+this.stuNo);
    }
}

var p=new Person(20,"李四");
p.sayHello();

var stu=new Student(22,'王五','123456');
stu.sayHello();

 通过这一小段代码可以引出 call和apply的区别,javascript中this的作用域等问题

原文地址:https://www.cnblogs.com/duanjt/p/6126737.html