javascript - 关于js的prototype问题,为什么会undefined?
PHP中文网
PHP中文网 2017-04-10 17:01:24
[JavaScript讨论组]
<script>
(function(){
    function _$(){
        this.str = 200;
    }
    _$.prototype = {
        name:(function(){
            return this.str;
        })(),
        type:function(){
            return this.str;
        },
    }
    window.$ = new _$();
})();

alert($.name);
alert($.type());
</script>

alert($.name);出错
alert($.type());正常

请教如何使$.name正常


补充(21:22)

name:(function(){ return this.str; })()
更改为
name:this.str
还是不行。。。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(4)
高洛峰
<script>
(function(){
    function _$(){
        this.str = 200;
    }
    _$.prototype = {
        name:(function(){
            return this.str;
        })(),
        type:function(){
            return this.str;
        },
    }
    window.$ = new _$();
})();

console.log($.name);//在定义赋值的时候name就被赋值为undefined,因为this为全局对象,其下没有str属性被定义
console.log($.type());//this为new _$()出的实力对象,有str属性,其值为200;
</script>

this只存在于函数体中,在函数被调用时其才有意义。

下面利用 Object.defineProperty方法及set/get属性描述器,可以实现你的需要
不知你要这样写代码的目的是什么

(function(){
        function _$(){
            this.str = 200;
            this.ddd="789";
        }

        _$.prototype = {
            type:function(){
                return this.str;
            }
        };

        Object.defineProperty(_$.prototype, 'name', {
                get: function() { return this.str; },
                set: function(newValue) { this.str = newValue; 
            }
        });

    window.$ = new _$();

})();

console.log($.name);
console.log($.type());
大家讲道理

楼上说的没错。 其实这里更确切的应该叫做IIFE(立即执行函数). 使用IIFE的时候里面的this都是执行window或者说是全局的global对象。 详情理解可以参考一下,js引擎解析js代码的过程。因为解析器会会首先解析函数,变量名。 如果你是IIFE他不会管你在那一层定义的。他会首先提取出来,在全局中执行。
所以你这样使用,执行的结果肯定是undefined的。
另外,你的第二种方法:

   function _$(){
        this.str = 200;
    }
    _$.prototype = {
        name:this.str,
        type:function(){
            return this.str;
        },
    }
    var $ = new _$();
    console.log($.name);

区分的点其实应该是this的指向问题,这里this指向的是_$.prototype。 而你在该原型链上并没有定义name,所以也是undefined

黄舟

楼上的答案都很对。
1.自执行的匿名函数关键字this是指向window对象,所以在原型方面中是做不到首先确定this指向一个示例对象
2.如果想在构造函数时机来确定原型对象的静态属性,那么直接在构造函数中写就可以了

(function(){
    function _$(){
        this.str = 200;
        _$.prototype.name = 200;
    }
    _$.prototype = {
        type:function(){
            return this.str;
        },
    }
    window.$ = new _$();
})();

console.log($.name);
console.log($.type());
PHPz

匿名函数this指向window。

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

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