• Javascript之Prototype


    1.原型设计模式

    在.Net中可以使用clone()来实现原型法

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

    2.javascript的方法可以分为三类

    类方法;对象方法;原型方法;

    举例说明:

    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 p =new People();

    p.Introduce();

    Peolple.Run();

    p.IntroduceChinese();

    3.延伸

    javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。
    A.prototype = new B();
    理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方 法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例。

    扩展1:

    function baseClass()
    {
      this.showMsg = function()
      {
         alert("baseClass::showMsg");   
      }
    }
    function extendClass()
    {
    }
    extendClass.prototype = new baseClass();
    var instance = new extendClass();
    instance.showMsg(); // 显示baseClass::showMsg

    如果extendClass也有showMsg方法:如下:

    扩展2:

    function baseClass()
    {
        this.showMsg = function()
        {
            alert("baseClass::showMsg");   
        }
    }
    function extendClass()
    {
        this.showMsg =function ()
        {
            alert("extendClass::showMsg");
        }
    }
    extendClass.prototype = new baseClass();
    var instance = new extendClass();
    instance.showMsg();//显示extendClass::showMsg

    实验证明:函数运行时会先去本体的函数中去找,如果找到则运行,找不到则去prototype中寻找函数。或者可以理解为prototype不会克隆同名函数。

    扩展3:

    如果我想使用extendClass的一个实例instance调用baseClass的对象方法showMsg怎么办?答案是可以使用call。

    extendClass.prototype = new baseClass();
    var instance = new extendClass();
    var baseinstance = new baseClass();
    baseinstance.showMsg.call(instance);//显示baseClass::showMsg
  • 相关阅读:
    JDK8中的 Lambda 表达式
    IDEA导入新项目jar包以及项目依赖tomcat设置
    idea导入项目,类为灰色,左下角有个红圈
    mysql服务忽然挂了,出现错误信息: Can’t connect to MySQL server on ‘localhost’ (10061)
    mysql、oracle、sql server连接信息
    mybatis中select * 中有字段,自己在起一个别名,然后实体类会使用哪个?
    pymongo的操作
    mongodb备份恢复
    mongodb建立索引
    mongodb聚合命令
  • 原文地址:https://www.cnblogs.com/yhhdream/p/4512235.html
Copyright © 2020-2023  润新知