zoukankan      html  css  js  c++  java
  • 构造函数模式

        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()都能用
  • 相关阅读:
    类和对象
    数组
    随笔3
    设计把所有的奇数移动到所有偶数前面的算法
    选择排序
    队列的链式存储结构
    循环队列
    一起玩算法(把所有相同的数字后移)
    判断序列B是否是序列A的连续子序列
    power bi创建切片器导航
  • 原文地址:https://www.cnblogs.com/lwwen/p/6231839.html
Copyright © 2011-2022 走看看