• 10JavaScript函数对象的prototype


     1 <script type="text/javascript">
     2 
     3 //  prototype:原型就是很多对象共享的一个内容,
     4 
     5     //-----------------为什么要有prototype原型对象?有什么用?--------------
     6                 function Person(uname, uage, uemail) {
     7                 //当在该构造函数中,通过this为对象注册成员的时候,那么将来创建的每个对象,都会保存一份这些成员的副本。
     8                     this.userName = uname;
     9                     this.userAge = uage;
    10                     this.userEmail = uemail;
    11 
    12                     this.sayHi = function () {
    13                         alert('Hi~_^大家好!,我叫:' + this.userName);
    14                     };
    15 
    16                     this.sayHello = function () {
    17                         alert('Hello 大家好,我今年' + this.userAge + '岁了。');
    18                     };
    19 
    20                     this.sayMorning = function () {
    21                         alert('good morning!');
    22                     };
    23                 }
    24 
    25 
    26                 //问题:p1 p2 p3创建的对象 每个对象都会包含3个属性 3个方法 占用内存空间
    27                 //其实是合理的,p1对象改变自己的属性不能影响到其他对象的成员,但是对于方法都保存一份就没有必要了
    28                 //当我们写一个对象的时候,对于对象中的属性单独创建一份没问题,但没必要没每个方法都保存一份空间
    29                 var p1 = new Person('张三', 18, 'mll@yahoo.com');
    30                 p1.userName = "fsdfsdf";
    31 
    32                 var p2 = new Person('李四', 19, 'pwb@yahoo.com');
    33 
    34                 var p3 = new Person('王五', 20, 'qg@yahoo.com');
    35 
    36 
    37                  function Person(email) {
    38             this.userEmail = email;
    39         }
    40 
    41       //把对象的所有的方法都注册到了Person.prototype对象上。(把方法注册到Person的原型上)
    42         Person.prototype.sayHi = function () {
    43             alert('Hi~我叫' + this.userName);
    44         };
    45 
    46         Person.prototype.sayHello = function () {
    47             alert('Hello ! 我:' + this.userAge + '岁了。');
    48         };
    49 
    50         Person.prototype.userName = '张三';
    51         Person.prototype.userAge = 18;
    52 
    53         Person.prototype.sayHi();
    54         Person.prototype.sayHello();
    55    
    56 
    57 

          //通过原型为一个已经编写好的类型增加一个扩展方法
          String.prototype.sayHello = function () {
          alert('我是字符串!!!');
          };

          String.prototype.addStyle= function (str) {
          return "★" + str + "★";
          };

          var msg = 'hello';
          msg.sayHello();
          alert(msg.addStyle(msg));




    58 59 60 61 62 </script>
  • 相关阅读:
    docker-machine create ,,,
    docker run with zabbix3.0
    mysql 官网
    取模性质
    欧涛最短路【记录最短路径】
    P4568 飞行路线【分层图最短路】
    CCF201403 无线网络【限制型最短路】
    POJ2449 【第k短路/A*】
    Feeding Time 【bfs求最大连通块】
    printf特殊用法
  • 原文地址:https://www.cnblogs.com/Forever-IT/p/5198837.html
Copyright © 2020-2023  润新知