继承方法

94 阅读1分钟

一.传统构造函数方法

function Person(name,sex,age)
{            
    this.name=name;           
    this.sex=sex;            
    this.age=age;       
}        
Person.prototype.showSelf=function()        
{            
    alert(`我是一个叫${this.name},今年${this.age}岁的${this.sex}孩`);        
}

每个函数都有一个prototype属性,这个属性是指向一个对象的引用,这个对象称为原型对象,原型对象包含函数实例共享的方法和属性,也就是说将函数用作构造函数调用(使用new操作符调用)的时候,新创建的对象会从原型对象上继承属性和方法。

简单讲原型prototype属性是函数所独有的,因为函数也是一种对象,所以函数也拥有__proto__constructor属性。

继承

1.构造函数的伪装--继承父级属性

function Person(name,sex,age)
{
    this.name=name;
    this.sex=sex;
    this.age=age;
}
Person.prototype.showSelf=function()
{
    alert(`我是一个叫${this.name},今年${this.age}岁的${this.sex}孩`);
}

call() :使用call方法调用函数并且指定上下文的’this’。(强制this指向)

该方法的作用和 apply() 方法类似,只有一个区别,就是call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

2.原型链 继承父一级的方法

<1>通过for..in遍历继承
function Worker(name,sex,age,job)
{
    //1构造函数的伪装--继承父级属性
    Person.call(this,name,sex,age);
    this.job=job;
}
<2>Object.create()方法

创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

Worker.prototype=Object.create(Person.prototype);

<3>调用构造函数继承
Worker.prototype=new Person();
Worker.prototype.showJob=function()
{
    alert("我的工作是"+ this.job);
}
var w1=new Worker("小米","男",20,"程序员");
w1.showSelf();
w1.showJob();

二.ECMA6class语法

class Person
{
    //class属性添加
    constructor(name,sex,age)
    {
        this.name=name;
        this.sex=sex;
        this.age=age;
    }
    showSelf()
    {
        alert(`我是一个叫${this.name},今年${this.age}岁的${this.sex}孩`);
    }
}
var p1=new Person("blue","男",18);
p1.showSelf();

extends 继承

class Worker extends Person
{
    constructor(name,sex,age,job) 
    {
        //继承到父一级的属性
        super(name,sex,age);
        this.job=job;
    }
    showJob()
    {
        alert("我的工作是"+ this.job);
    }
}
var w1=new Worker("小米","男",20,"程序员");
w1.showSelf();
w1.showJob();

super关键字用于访问和调用一个对象的父对象上的函数。