扫码关注官方订阅号
function name() { this.prototype.age = "15"; };
光阴似箭催人老,日月如移越少年。
为什么你不单步看看?
就算不单步,看错误提示都应该知道是怎么回事儿吧。
单纯想要程序不报错,很简单:
function name(){ this.prototype = {}; this.prototype.age = "15"; };
构造函数的prototype,和this指向实例的prototype不是一回事儿
如果你想直接在实例上操作类的prototype,你需要
类
function name(){ const type = Object.getPrototypeOf(this); type.age = "15"; };
调用 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
this
实例
this.prototype
属性
FUNCTION.prototype
因为函数对象才有prototype属性,函数里的this是new构造器时候返回的对象,并不是个函数对象。
你可以先console.log一下this function name(){console.log(this);};name();看看结果就知道为什么了
实例没有prototype属性,你这样写会给这个对象强加一个名为prototype的属性,跟原型链无关。应该操作构造函数的prototype属性,或者使用实例的_proto_属性(在webkit内核中)。
prototype
_proto_
可以结合你上一个Toms.mono那个问题考虑一下 :)
先弄明白this的是啥,函数的四种调用模式,你这个属于构造器调用
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
为什么你不单步看看?
就算不单步,看错误提示都应该知道是怎么回事儿吧。
单纯想要程序不报错,很简单:
构造函数的prototype,和this指向实例的prototype不是一回事儿
如果你想直接在实例上操作
类的prototype,你需要调用 name() 时,var obj = new name()。
this是实例对象this.prototype实例对象的属性原型必须用
FUNCTION.prototype你可以先console.log一下this
function name(){
console.log(this);
};
name();
看看结果就知道为什么了
实例没有
prototype属性,你这样写会给这个对象强加一个名为prototype的属性,跟原型链无关。应该操作构造函数的
prototype属性,或者使用实例的_proto_属性(在webkit内核中)。可以结合你上一个Toms.mono那个问题考虑一下 :)
先弄明白this的是啥,函数的四种调用模式,你这个属于构造器调用