构造函数相关笔记

2019-02-28  本文已影响0人  UmustHU

es5环境下写构造函数

//创建构造函数
function Person(name){
    //定义属性
    this.name = name
}
//定义方法
Person.prototype.showName = function(){
    return `my name is ${this.name}`
};
Person.prototype.showAge = function(age){
    this.age = age;
    return `my age is ${this.age}`
};
//创建一个实例
let p = new Person('bob','man');
//调用
console.log(p.sex);
console.log(p.showname());
console.log(p.showage(18));

继承

function Children(name,boy){
    //继承父级属性
    Person.call(this,name);
    //定义子级自己的属性
    this.boy = boy;
}
//继承父级的方法
Children.prototype = new Person();
//定义子级自己的方法
Children.prototype.sayWord = function(){
    return `i like ${this.boy}`;
};
//创建子级的实例
let c = new Children('cindy','girl','bob');
//打印父级继承过来的属性,调用父级继承过来的方法
console.log(c.sex);
console.log(c.showname());
console.log(c.showage(16));
//调用子级自己的方法
console.log(c.sayword());

es6环境下的构造函数

//创建构造函数
class Father{
    constructor(name,sex){
        //定义属性
        this.name = name;
        this.sex = sex;
    }
    //定义方法
    showName(){
        console.log('father fn showName is running');
        return `my name is ${this.name}`;
    }
    showAge(age){
        this.age = age;
        return `my age is ${this.age}`;
    }
}
//创建实例
let f = new Father('bob','man');
//打印属性,调用方法
console.log(f.name);
console.log(f.showName());
console.log(f.showAge(18));

继承

class Children extends Father{
    constructor(name,sex,hobby){
        //继承属性
        super(name,sex);
        //添加子级自己的属性
        this.hobby = 'sing'
    }
    //属于子级自己的方法
    showLike(data){
        return `i like ${data}`
    }
    //定义与父级同名的方法会把父级的方法覆盖
    showName(){
        //因此需要通过super去调用父级的方法,但是父级方法里面的return拿不到
        super.showName();
        console.log('children fn showAge is running');
    }
}
//创建子级的实例
let c = new Children('cindy','girl');
//从父级继承的属性和方法
console.log(c.name)
console.log(c.showAge(16));
//属于子级自己的属性和方法
console.log(c.showLike('bob'));
console.log(c.hobby);
//覆盖了父级的方法
console.log(c.showName());
//返回结果
//father fn showName is running    父级函数被调用
//children fn showAge is running    子级自己的操作
//undefined  但是由于子级没有return数据,而且又无法获取父级函数return的数据,因此undefined

class的set和get

class Demo{
    constructor(){
    }
    set name(val){
        console.log('set name='+val)
    }
    get name(){
        console.log('get name')
    }
}
let d = new Demo();
d.name = 'lili';
console.log('-----------------我是分割线------------------')
let a = d.name;
//输出结果
//set name=lili
//-----------------我是分割线------------------
//get name

clsss的静态方法

class Demo{
    constructor(){
        this.name = 'bob';
        this.age = 18;
    }
    showName(){
        console.log(this.name)
    }
    static showAge(){
        console.log('static')
    }
}
let d = new Demo();
d.showName();
//返回结果
//bob
Demo.showName();
//返回结果
//Uncaught TypeError: Demo.showName is not a function
d.showAge();
//返回结果
//Uncaught TypeError: d.showAge is not a function
Demo.showAge();
//返回结果
//static
上一篇 下一篇

猜你喜欢

热点阅读