Skip to content

Instantly share code, notes, and snippets.

@laispace
Created February 8, 2015 08:50
Show Gist options
  • Select an option

  • Save laispace/8956668723a0422f90e1 to your computer and use it in GitHub Desktop.

Select an option

Save laispace/8956668723a0422f90e1 to your computer and use it in GitHub Desktop.

Revisions

  1. laispace created this gist Feb 8, 2015.
    51 changes: 51 additions & 0 deletions pattern-decorator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    // pattern-decorator.js

    // ===== 1. let instance has new functions =====
    function Person (name, age) {
    this.name = name;
    this.age = age;
    }

    Person.prototype.say = function (something) {
    console.log(this.name, 'says: ', something);
    };

    // now we new a person
    var person1 = new Person('xiaolai-1', 18);
    // let me say hi
    person1.say('hi');

    // then we new another person
    var person2 = new Person('xiaolai-2', 19);
    // let me say hello
    person2.say('hello');
    // and le me have the ability to run
    person2.run = function (distance) {
    console.log(this.name, 'runs: ', distance, 'miles');
    };
    // NOTE that person2 can run but person1 can not.

    // ===== 2. let instance has adding propertity =====

    var person3 = new Person('xiaolai-3', 20);

    function AddAge5 (person) {
    person.age += 5;
    }
    function AddAge10 (person) {
    person.age += 10;
    }
    function AddAge20 (person) {
    person.age += 20;
    }

    // now let my age inscrease!
    AddAge5(person3);
    console.log(person3.age);

    AddAge10(person3);
    console.log(person3.age);

    AddAge20(person3);
    console.log(person3.age);