• 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
  • 相关阅读:
    笔记44 Hibernate快速入门(一)
    tomcat 启用https协议
    笔记43 Spring Security简介
    笔记43 Spring Web Flow——订购披萨应用详解
    笔记42 Spring Web Flow——Demo(2)
    笔记41 Spring Web Flow——Demo
    Perfect Squares
    Factorial Trailing Zeroes
    Excel Sheet Column Title
    Excel Sheet Column Number
  • 原文地址:https://www.cnblogs.com/yhhdream/p/4512235.html
Copyright © 2020-2023  润新知