• Javascript原型


      创建的每一个函数都有一个prototype属性,它实则是一个对象。

      利用prototype构造原型,它的用途是共享原型中的属性和方法。

      如果是实例方法,不同的实例化,它们的地址是不同的;而利用原型,实例在内存中是共享的。

      1.使用构造函数创建原型:

     function Box(){}
    
      Box.prototype.name="Lee";
      Box.prototype.age=100;
      Box.prototype.run=function(){
    
        return this.name+this.age+"运行中。。。";
    
      }
    
      var box=new Box();
    
      alert(box.run());
    

      利用constructor可以得到构造函数本身,而__proto__则指向原型对象。

      判断一个实例化是不是指向原型对象,可以使用isPrototypeOf()。只要实例化了,就会指向。

      可以用delete来删除原型中的属性。如:

       delete box.prototype.name;
    

      判断实例中时是否存在某属性,可使用hasOwnProperty(“属性”)方法。

      不管实例属性或原型属性,判断方法为:

      alert(“name” in box); 

      2.使用字面量方式创建原型对象:

       functon Box(){}
    
       Box.prototype={
          name:"Lee",
          age:100,
          run:function(){
            return this.name+this.age+"运行中...";
          }
    
       }
    
       var box=new Box();
       alert(box.run());
    

      3.调用原型方法和为原型添加方法

        Array.prototype.sort;       
        String.prototype.substring;
        Box.prototype.addstring=function(){   //为Box添加addstring方法
    
          ......
        }

      4.原型的缺点

      下面看一段代码:

    funtion Box(){}
    Box.prototype={
        constructor:Box,
        name:"Lee",
        age:100,
        family:["哥哥",“姐姐”,“妹妹”],
        run:function(){
             return this.name+this.age+"运行中..";
    
        }
    }
    
    var box1=new Box();
    alert(box1.family);
    box1.family.push("弟弟");
    alert(box1.family);

    var box2=new Box();
    alert(box2.family); //共享了box1的属性,导致了错误

      我们用如下方式既保持了独立,又实现了共享。即组合模式:构造函数+原型。

    function Box(name,age){       //保持独立用构造函数
        this.name=name;
        this.age=age;
        this.family=["哥哥","姐姐","妹妹"];
    }
    
    Box.prototype={
        constructor:Box,
        run:function(){
            return this.name+this.age+"运行中...";
    }
    
    var box1=new Box();
    box1.family.push("弟弟");
    alert(box1.family);
    
    var box2=new Box();
    alert(box2.family);     //没有弟弟

      而Javascript作为面向对象的语言,可以将原型封装到构造函数里。但原型初始化会执行很多次,可以使用如下语句只让它初始化一次:

      if(typeof this.run!=function){

           原型
      }

  • 相关阅读:
    day-7
    Redis数据库 : 基础
    MongoDB与python交互
    MongoDB数据库 : 管道,用户管理,副本集等
    MongoDB数据库 : 基础
    MySQL数据库 : 自关联,视图,事物,索引
    MySQL数据库 : 查询语句,连接查询及外键约束
    MySQL数据库 : 基本语句
    数据结构与算法 : 树与遍历
    python__标准库 : 测试代码运行时间(timeit)
  • 原文地址:https://www.cnblogs.com/tangzhirong/p/4804233.html
Copyright © 2020-2023  润新知