• JS的原型链的相关操作


    JS的原型链的相关操作

    JS的prototype

    1.javascript中的每个对象都有prototype属性,
    2.每创建一个函数,该函数就会自动带有一个 prototype 属性。该属性是个指针,指向了一个对象,我们称之为 原型对象。
    3.Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。
    4.每一个构造函数都有一个属性叫做原型。这个属性非常有用:为一个特定类声明通用的变量或者函数。
    such as:

    function Test(){}
    alert(Test.prototype); // 输出 "Object"
    

    在这里插入图片描述
    原型对象上默认有一个属性 constructor,该属性也是一个指针,指向其相关联的构造函数。
    通过调用构造函数产生的实例,都有一个内部属性,指向了原型对象。所以实例能够访问原型对象上的所有属性和方法。

      

      所以三者的关系是,每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。通俗点说就是,实例通过内部指针可以访问到原型对象,原型对象通过constructor指针,又可以找到构造函数。

    原型的设计模式

    原型法的主要思想是,现在有1个类A,我想要创建一个类B,这个类是以A为原型的,并且能进行扩展。我们称B的原型为A。

    for Example:

    function People(name)
    {
      this.name=name;
      //对象方法
      this.Introduce=function(){
        alert("My name is "+this.name);
      }
    }
    //类方法
    People.Run=function(){
      alert("I can run");
    }
    //原型方法
    People.prototype.IntroduceChinese=function(){
      alert("我的名字是"+this.name);
    }
     
    //测试
    var p1=new People("Windking");
    p1.Introduce();
    People.Run();
    p1.IntroduceChinese();
    

    在这里插入图片描述
    区别就在于相关的使用方式不同。

    from: https://www.cnblogs.com/wulihong/p/8906231.html
    遇到过一个面试题目:
    Date对象中追加format方法 ,因为date本来没有格式化方法,怎么添加上去

    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //時間
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()             //ミリ 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1,
                        (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    
    咫尺远近却无法靠近的那个你,才敢让你发觉你并不孤寂
  • 相关阅读:
    Convert to a source folder or rename it.
    git revert 后悔了 还原修改前的版本 + git 常用命令
    android switch语句报错:case expressions must be constant expressions
    解读ContentResolver和ContentProvider
    sdk命令
    向Android模拟器中批量导入通讯录联系人
    Rational Rose2007下载安装教程以及问题处理
    java代码打包成jar以及转换为exe
    Timusoj 1982. Electrification Plan
    poj 3254 Corn Fields
  • 原文地址:https://www.cnblogs.com/tcz1018/p/15243512.html
Copyright © 2020-2023  润新知