无法在javaScript中向原型添加属性

时间:2014-04-15 14:06:21

标签: javascript

试图更好地理解原型,所以我去了我的控制台并输入了这个:

    function Dog(){}

    Dog.prototype.breed = breed;

    Dog.prototype.talk  = function(){

    console.log('I\'m a ' + this.breed);

    };


    dog1 = new Dog();


    dog1.breed = 'poodle';

    dog1.talk();

    //This is what I get...
    //ReferenceError: breed is not defined

更新我使用了null并且效果很好....但有趣的是,使用Dog.prototype.name = name;有效!

    Dog.prototype.name = name;
    //Dog.prototype.breed = null;
    Dog.prototype.talk  = function(){

    console.log('my name is ' + this.name );

    };


    dog1 = new Dog();

    dog1.name = 'charly';
    //dog1.breed = 'poodle';

    dog1.talk();

1 个答案:

答案 0 :(得分:2)

Dog.prototype.breed = breed;

您尚未定义breed。如果您想提供某种默认品种,请尝试:

Dog.prototype.breed = "mutt";