Why declare properties on the prototype for instance variables in JavaScript

后端 未结 4 1853
清酒与你
清酒与你 2020-12-12 21:13

I\'m trying to get my head around this black art called JavaScript - and, I must admit, pretty excited about it. I\'ve been looking at code examples, mainly from \"easeljs\"

4条回答
  •  独厮守ぢ
    2020-12-12 21:51

    Yeah, I agree the prototype can be used for default values of properties (variables). The constructor function doesn't need to declare a property; it may be done conditionally.

    function Person( name, age ) {
        this.name = name;
    
        if ( age ) {
            this.age = age;
        }
    }
    
    Person.prototype.sayHello = function() {
        console.log( 'My name is ' + this.name + '.' );
    };
    
    Person.prototype.sayAge = function() {
        if ( this.age ) {
            console.log( 'I am ' + this.age + ' yrs old!' ); 
        } else {
            console.log( 'I do not know my age!' );
        }
    };
    
    Person.prototype.age = 0.7;
    
    //-----------
    
    var person = new Person( 'Lucy' );
    console.log( 'person.name', person.name ); // Lucy
    console.log( 'person.age', person.age );   // 0.7
    person.sayAge();                           // I am 0.7 yrs old!
    

    See how Lucy's age is conditionally declared and initialized.

提交回复
热议问题