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()都能用
  • 相关阅读:
    windows phone 网络开发三部曲(一)各种包的各种抓法
    Windows phone UI虚拟化和数据虚拟化(二)
    Windows phone UI虚拟化和数据虚拟化(一)
    LongListSelector 控件 在 wp7 和wp8中的不同之处
    wp8 longlistselector 动态加载datatemplate
    解读Python发送邮件
    浅谈Python时间模块
    中文分词技术一:概念
    MySQL常用命令
    初步认识Hive
  • 原文地址:https://www.cnblogs.com/lwwen/p/6231839.html
Copyright © 2011-2022 走看看