我为网站开发了某种Jcrop初始化,我设法创建了自己的命名空间.我的问题是关于这个关键字.每次我必须在任何回调函数中访问我的基础对象“aps”时,我必须将它包装在一个变量中(我选择了这个单词).有没有更好的方法呢?例如,我可以使用call或apply方法吗?这只是一个命名空间,所以我可以使用简单的aps.methodName但是为了这个例子,请不要介意.这是我的源代码:
var aps;

$(function(){
    aps = function(){

        //  private
        //  variables

        var bgColor = '#f5f5f5';
        var threshold = 370;
        var threshold_width = 800;

        return {
            tmpl                :       $('#jcrop-template').html(),upl_cont            :       {},form                :       {},logo_img            :       new Image(),jcrop_api           :       null,scaled_logo_url         :       '',image_filename          :       '',original_image_filename     :       '',mime                :       '',trueSize            :       '',jcrop_init          :       function (oiFrameRes){
                $('#logo_upload_form').find('img').hide();
                this.scaled_logo_url = oiFrameRes.image_url;
                this.logo_url = oiFrameRes.original_image_url;
                this.original_image_filename = oiFrameRes.original_image_filename;
                this.image_filename = oiFrameRes.image_filename;
                this.mime = oiFrameRes.mime;
                this.upl_cont = $('#faceBox div#upload-container-d');
                this.logo_img = new Image();
                this.logo_img.that      =   this;
                this.logo_img.name      =   'logo';
                this.logo_img.onload    =   function(){
                    this.true_width=this.width;
                    this.true_height=this.height;
                    this.that.resize_image();
                    this.that.resize_faceBox();
                    this.that.display_image();
                }
                this.logo_img.src = this.logo_url;
            },resize_image            :       function(){
                this.trueSize = '';
                if(typeof (this.oSettings.trueSize)!=='undefined') delete(this.oSettings.trueSize);
                if (this.logo_img.width > threshold){
                    if (this.logo_img.width > threshold_width){
                        this.trueSize = [ this.logo_img.width,this.logo_img.height ];
                        this.logo_img.height = this.logo_img.height / (this.logo_img.width / threshold_width);
                        this.logo_img.width = threshold_width;
                    }
                }
            },resize_faceBox          :       function(){
                    var width = (this.logo_img.width > threshold) ? this.logo_img.width : threshold ;
                    $('#faceBox').css({
                        left    :   $(window).width() / 2 - width / 2
                    }).
                    find('div.change-size').css({'width': width+30});
            },display_image : function (){
                if (this.jcrop_api === null) {
                    $logo_img = $(this.logo_img).css({'display':'block','margin-left':'auto','margin-right':'auto'})
                    if (this.upl_cont.find('#logo-container-d>img').length > 0){
                        if (this.upl_cont.find('#logo-container-d>img').attr('src').length > 0){
                            this.upl_cont.find('#logo-container-d').empty().append($logo_img);
                        }
                    }
                    else {
                        this.upl_cont.append(this.tmpl).find('#logo-container-d').append($logo_img);
                    }

                    var that = this;
                    if (typeof (this.upl_cont.find('#jcrop-menu1 a').data('events')) === 'undefined'){
                        this.upl_cont.find('#jcrop-menu1 a').click(function(){
                            if (this.href.indexOf('#crop')>-1){
                                $(this).closest('div').hide();
                                that.upl_cont.find('#jcrop-menu2').show();
                                that.setup_crop();
                            }
                            if (this.href.indexOf('#close')>-1){
                                manageIframeResponse();
                            }   
                            location.hash = '';
                            return false;
                        });
                    }
                }
                else {
                    this.reset();
                }
            },reset : function(){
                $('#jcrop-menu2',this.upl_cont).find('a').unbind('click').end().hide();
                $('#jcrop-coords-f',this.upl_cont).find('input[type="text"]').each(function(){this.value="";}).end().hide();
                $('#jcrop-menu1',this.upl_cont).find('a').unbind('click').end().show();
                this.jcrop_api.destroy();
                this.jcrop_api=null;
                this.display_image();
            },send_form : function (){
                var sPost = $(this.form).find('input[name="image_filename"]').val(this.image_filename).end()
                        .find('input[name="original_image_filename"]').val(this.original_image_filename).end()
                        .find('input[name="mime"]').val(this.mime).end()
                        .find('input[name="user_url"]').val($('#logo_upload_base_url').val()).end()
                        .find('input[name="user_key"]').val($('#logo_upload_user_key').val()).end()
                        .serialize();

                $.ajax({
                    url:'iframe_upload.PHP',type:'POST',data: sPost,success : function(response){
                        manageIframeResponse();
                    },dataType : 'json'
                });
            },setup_crop : function (){

                var that = this;
                if (this.jcrop_api === null) {
                    this.form = this.upl_cont.find('form#jcrop-coords-f').get(0);
                    this.upl_cont.find('#jcrop-menu2>a').click(function(){ that.send_form();return false; });
                    this.updateForm = function (){
                        var c = arguments[0];
                        that.form.x1.value=c.x;
                        that.form.x2.value=c.x2;
                        that.form.y1.value=c.y;
                        that.form.y2.value=c.y2;
                        that.form.h.value=c.h;
                        that.form.w.value=c.w;
                    }

                    this.oSettings.onSelect = this.updateForm;
                    if (typeof (this.trueSize) !== 'string' && $.isArray(this.trueSize)){
                        $.extend(this.oSettings,{'trueSize':this.trueSize});
                    }
                    $('#faceBox #logo-container-d>img').Jcrop( this.oSettings,function(){

                        that.jcrop_api = this;
                        var _x1 = (that.logo_img.true_width*0.1).toFixed();
                        var _y1 = (that.logo_img.true_height*0.1).toFixed();
                        var _x2 = (that.logo_img.true_width*0.9).toFixed();
                        var _y2 = (that.logo_img.true_height*0.9).toFixed();
                        that.jcrop_api.setSelect([0,that.logo_img.true_width,that.logo_img.true_height]);
                        that.jcrop_api.animateto([_x1,_y1,_x2,_y2]);
                    });
                }
            },updateForm : function (){},oSettings : {
                onSelect:'',onChange:'',keySupport: false,bgColor:bgColor,aspectRatio:1,minSize:[0,0]
            }
        }
    }();

    $(document).bind('afterClose.faceBox',function() { 
        if (aps.jcrop_api !=null) {
            aps.jcrop_api.destroy();
            aps.jcrop_api=null;
        }
    });
});

解决方法

无论何时使用函数调用*调用函数,此值都将设置为全局变量(或在严格模式下未定义) – 即使从方法调用函数也是如此.道格拉斯·克罗克福德实际上已将此描述为该语言的一个缺陷.

将此值保存到函数可以访问的变量中是处理此问题的标准方法.

如果您真的想控制回调中的内容,可以使用apply或call.两者都将您想要设置的第一个参数作为第一个参数.不同之处在于apply期望所有函数的参数作为数组传递,而call期望您单独列出它们.

因此,如果在你的ajax回调中,你想调用manageIframeResponse,请传递ajax调用的响应(我知道你的例子没有传递响应,我只是说明你将如何做),并将其值设为与当前对象相同,您可以这样做:

var self = this;
$.ajax({
    success : function(response){
        manageIframeResponse.apply(self,[response]); //<--- apply wants your arguments in array form
    }
});

或者,由于您的参数尚未采用数组形式,因此您可以更简单地使用调用

var self = this;
$.ajax({
    success : function(response){
        manageIframeResponse.call(self,response); //<---call takes the arguments listed out one at a time
    }
});

*
有不同的方法来调用函数.

函数调用意味着您只是调用恰好位于当前范围内的函数:

foo() //inside foo,this will be the global object (or undefined in strict mode)

方法调用意味着您正在调用附加到对象的函数

myObj.foo() //inside foo,this will be myObj

这里有一个例子,如果你不小心,这会让你感到沮丧.

function objCreator() {
    var y = "There";

    function privateFunc() {
        alert(y); //alerts There as expected
        alert(this.someField); //undefined:  whoops - this is the global object,}                          //so there's no someField 

    return {
        x: "Hi",someField: "blah",foo: function () {
            alert(this.x);
            privateFunc();
        }
    };
}

javascript – 如何在我的对象范围之外调用’this’?的更多相关文章

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. js中‘!.’是什么意思

  3. InnoDB 和 MyISAM 引擎恢复数据库,使用 .frm、.ibd文件恢复数据库

  4. Error: Cannot find module ‘node:util‘问题解决

    控制台 安装 Vue-Cli 最后一步出现 Error: Cannot find module 'node:util' 问题解决方案1.问题C:\Windows\System32>cnpm install -g @vue/cli@4.0.3internal/modules/cjs/loader.js:638 throw err; &nbs

  5. yarn的安装和使用(全网最详细)

    一、yarn的简介:Yarn是facebook发布的一款取代npm的包管理工具。二、yarn的特点:速度超快。Yarn 缓存了每个下载过的包,所以再次使用时无需重复下载。 同时利用并行下载以最大化资源利用率,因此安装速度更快。超级安全。在执行代码之前,Yarn 会通过算法校验每个安装包的完整性。超级可靠。使用详细、简洁的锁文件格式和明确的安装算法,Yarn 能够保证在不同系统上无差异的工作。三、y

  6. 前端环境 本机可切换node多版本 问题源头是node使用的高版本

    前言投降投降 重头再来 重装环境 也就分分钟的事 偏要折腾 这下好了1天了 还没折腾出来问题的源头是node 使用的高版本 方案那就用 本机可切换多版本最终问题是因为nodejs的版本太高,导致的node-sass不兼容问题,我的node是v16.14.0的版本,项目中用了"node-sass": "^4.7.2"版本,无法匹配当前的node版本根据文章的提

  7. 宝塔Linux的FTP连接不上的解决方法

    宝塔Linux的FTP连接不上的解决方法常见的几个可能,建议先排查。1.注意内网IP和外网IP2.检查ftp服务是否启动 (面板首页即可看到)3.检查防火墙20端口 ftp 21端口及被动端口39000 - 40000是否放行 (如是腾讯云/阿里云等还需检查安全组)4.是否主动/被动模式都不能连接5.新建一个用户看是否能连接6.修改ftp配置文件 将ForcePassiveIP前面的#去掉 将19

  8. 扩展element-ui el-upload组件,实现复制粘贴上传图片文件,带图片预览功能

  9. 微信小程序canvas实现水平、垂直居中效果

    这篇文章主要介绍了小程序中canvas实现水平、垂直居中效果,本文图文实例代码相结合给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

  10. 使用HTML5做的导航条详细步骤

    这篇文章主要介绍了用HTML5做的导航条详细步骤,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部