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的是啥,函数的四种调用模式,你这个属于构造器调用
为什么你不单步看看?
就算不单步,看错误提示都应该知道是怎么回事儿吧。
-
单纯想要程序不报错,很简单:
function name(){ this.prototype = {}; this.prototype.age = "15"; };
构造函数的prototype,和this指向实例的prototype不是一回事儿
-
如果你想直接在实例上操作
类
的prototype,你需要function name(){ const type = Object.getPrototypeOf(this); type.age = "15"; };
实例没有prototype
属性,你这样写会给这个对象强加一个名为prototype
的属性,跟原型链无关。
应该操作构造函数的prototype
属性,或者使用实例的_proto_
属性(在webkit内核中)。