• 组合使用构造函数模式和原型模式创建自定义类型


      构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。看下面的例子:

    function Person(name, age, job){
      this.name = name;
      this.age = age;
      this.job = job;
      this.friends = ["Shelby", "Court"];
    }
    
    Person.prototype = {
      constructor: Person,
      sayName: function(){
        alert(this.name);
      }
    }
    
    var person1 = new Person("Nicholas", 29, "Software Engineer");
    
    var person2 = new Person("Greg", 27, "Doctor");
    
    person1.friends.push("Van");
    
    alert(person1.friends);          // "Shelby, Count, Van"
    
    alert(person2.friends);          // "Shelby, Count"
    
    alert(person1.friends === person2.firends);          // false
    
    alert(person1.sayName === person2.sayName);          // true

      在这个例子中,实例属性都是在构造函数中定义的,而由所有实例共享的属性constructor和方法sayName()则是在原型中定义的。而修改了person1.firends(向其中添加一个新字符串),并不会影响到person2.friends,因为它们分别引用了不同的数组。

      这种构造函数和原型混成的模式,是目前在ECMAScript中使用最广泛、认同度最高的一种创建自定义类型的方法。可以说,这是用来定义引用类型的一种默认模式。

  • 相关阅读:
    KafkaOffsetMonitor
    锋利的KATANA
    用grunt搭建自动化的web前端开发环境
    网上书店订单功能的实现
    作用域和控制器
    使用CLK.AspNet.Identity提供以角色为基础的访问控制(RBAC)
    ABP日志管理
    .NET开源项目
    服务总线
    Message解析流程(转)
  • 原文地址:https://www.cnblogs.com/linxd/p/4485405.html
Copyright © 2020-2023  润新知