菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
479
0

构造函数模式

原创
05/13 14:22
阅读数 15294
    function student(props){
        this.name=props.name || '匿名';//默认是匿名
        this.grade=props.grade || 1;
    }
    student.prototype.hello=function(){
        console.log('hello '+this.name);
    }
    function createStudent(props){
        return new student(props||{})
    }
    var xiaoming=createStudent({
        name:'xiaoming'
    });
    xiaoming.hello();//hello xiaoming

传进一个数组 

    function animal(name,age,grade){
        this.name=name;
        this.age=age;
        this.grade=grade;
    }
    animal.prototype.hello=function(){
        console.log('hello '+this.name);
    }
    var chicken=new animal('chicken',3,12);
    chicken.hello();//hello chicken

我理解的构造函数就是用new()实例化去构造

 

看了原型继承,发现原型继承不了

所以就看代码

    function student(name){
        this.name=name||'unname';
    }
    student.prototype.hello=function(){
        console.log('hello'+this.name)
    }
    function cat(grade){
        student.call(this,grade);
        this.grade=grade||12
    }

    var a=new cat()//a.name=unname,a.grade=12,a.hello() is not a function不可以继承student的原型,
    function f(){}
    f.prototype=student.prototype;
    cat.prototype=new f()
    var b=new cat();//b.name=unname,b.grade=12,b.hello()='hello unname'可以继承student的原型

通过call来调用继承,并绑定this

 也可以用class来extends

class student{
    constructor(name){
        this.name=name
    }
    hello(){
        console.log('hello'+this.name)
    }
}
class cat extends student{
    constructor(name,grade){
        super(name);
        this.grade=grade;
    }
    myGrade(){
        console.log('my grade is'+this.grade)
    }
}
var a=new cat()
//a.name,a.hello(),a.grade,a.myGrade()都能用

 

相关热门文章

发表评论

0/200
479 点赞
0 评论
收藏
为你推荐 换一批