javascript - prototype不能放在this后面?
大家讲道理
大家讲道理 2017-04-11 12:16:55
[JavaScript讨论组]
    function name()
    {
        this.prototype.age = "15";
    };
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(8)
巴扎黑
  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";
    };
黄舟

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

PHP中文网
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

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

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

阿神

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

ringa_lee

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

阿神

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号