首页 > person1.prototype.name = 'tom'为什么是错的?

person1.prototype.name = 'tom'为什么是错的?

        function Person(){     
            Person.prototype.name = "Nicholas";
            }
      
        var person1 = new Person();
        
        person1.prototype.name = 'tom';
        
        alert(person1.name);

为何不能这样:person1.prototype.name = 'tom';修改prototype中的属性?


在实例上不能使用prototype


对象才有prototype,实例化后不能再这么写


prototype是针对构造器函数的,一般对象没有prototype属性。
prototype属性一般用来设置对象方法。
题主的Person构造函数也有些问题,如下写比较好。

  //构造器--类
  var Person = (function(){
    var Person = function(){
      // enforces new
      if (!(this instanceof ConstructorName)) {
        return new ConstructorName(args);
      }
      // constructor body
      this.name = "Nicholas";//设置对象name属性默认值
    };
    Person.prototype.getName = function(){
      return this.name;
    };
    Person.prototype.setName = function(name){
      this.name = name;
    };
    return Person;
  })();

  //对象
  var person1 = new Person();
  console.log(person1.name);//Nicholas
  person1.name = 'tom';
  console.log(person1.name);//tom
  person1.setName('jay');
  console.log(person1.name);//jay
  console.log(person1.getName());//jay
【热门文章】
【热门文章】