首页 > prototype不能放在this后面?

prototype不能放在this后面?

    function name()
    {
        this.prototype.age = "15";
    };

因为函数对象才有prototype属性,函数里的this是new构造器时候返回的对象,并不是个函数对象。

调用 name() 时,var obj = new name()。


function name(){
  this.prototype = this.prototype || {};
  this.prototype.age = "15";
};
var john = new name();
console.log(john.prototype); //{age:"15"}
name();
console.log(prototype);//{age:"15"}
console.log(window.prototype)//{age:"15"}

this实例 对象
this.prototype 实例对象的属性
原型必须用 FUNCTION.prototype


你可以先console.log一下this
function name(){
console.log(this);
};
name();
看看结果就知道为什么了


可以结合你上一个Toms.mono那个问题考虑一下 :)


先弄明白this的是啥,函数的四种调用模式,你这个属于构造器调用


  1. 为什么你不单步看看?

  2. 就算不单步,看错误提示都应该知道是怎么回事儿吧。

  3. 单纯想要程序不报错,很简单:

    function name(){
        this.prototype = {};
        this.prototype.age = "15";
    };
  4. 构造函数的prototype,和this指向实例的prototype不是一回事儿

  5. 如果你想直接在实例上操作的prototype,你需要

    function name(){
        const type = Object.getPrototypeOf(this);
        type.age = "15";
    };

实例没有prototype属性,你这样写会给这个对象强加一个名为prototype的属性,跟原型链无关。
应该操作构造函数的prototype属性,或者使用实例的_proto_属性(在webkit内核中)。

【热门文章】
【热门文章】