javascript - js嵌套的对象原型里面怎么制定this相同

查看:133
本文介绍了javascript - js嵌套的对象原型里面怎么制定this相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

function person(){
        this.name="abc";
    }
    person.prototype={
        showName:function(){
            console.log(this.name);
        },
        info:{
            showName:function(){
                var _this=this;
                console.log(_this.name);
            }
        }
    }

代码里面两处_this指向不同,怎么让_this都指向person内部,还有在写插件时有什么办法只写一次_this,然后全局都可以调用,注意!!千万不要提供在person外面设置全局变量_this这种办法!!!

解决方案

var person;
;(function(){
    var _this;//外面照样获取不到
    person = function(){
        _this = this
        this.name="abc";
    }
    person.prototype={
        showName:function(){
            console.log(this.name);
        },
        info:{
            showName:function(){
                var _this=this;
                console.log(_this.name);
            }
        }
    }
})()

这篇关于javascript - js嵌套的对象原型里面怎么制定this相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆