• 构造函数模式


        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()都能用
  • 相关阅读:
    sftp 使用笔记
    python-day001获取mac地址
    tomcat 修改端口
    mysql 封装与使用
    redis 封装使用
    centos7安装jenkins
    securecrt设置编码、字体、编码
    linux操作系统上路由管理维护
    ElasticSearch操作和使用指南
    sqlyog连接mysql错误码2058
  • 原文地址:https://www.cnblogs.com/lwwen/p/6231839.html
Copyright © 2020-2023  润新知