2020-9-17日:组合使用构造函数模式和原型模式 ;

  • 6.2.4 组合使用构造函数模式和原型模式  ;
  1. 构造函数模式用于定义实 例属性;
  2. 原型模式用于定义方法和共享的属性;
  3. 这种混成模式还支持向构造函数传递参 数;
  4. 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.friends); // false
        alert(person1.sayName === person2.sayName); // true

     

posted @ 2021-01-05 10:50  Amber丶Li  阅读(46)  评论(0)    收藏  举报