Javascript范围引用外部对象 [英] Javascript scope referencing outer object

查看:72
本文介绍了Javascript范围引用外部对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我为Javascript使用了称为 Joose 的元类框架,该框架使我可以使用更优雅的类语法-但我不知道如何从类声明的更深层方法中引用对象的范围.我还使用require.js进行依赖管理...

Basically, I use a meta-class framework called Joose for Javascript that allows me to make use of a more elegant class syntax - but I don't know how I might go about referencing the scope of the object from within deeper methods of the class declaration. I also use require.js for dependemcy management...

这是一个示例类定义:

   define([
      'jquery',
      'handlebars',
   ], function($, Handlebars){

      var MyClass = Class("MyClass", {

         //inheritance         
         isa: SuperClass,

         //instance vars
         has: {

            hello:{
               is: 'r',
               init: 'Hi There!',
            },

            someVarToBeSetUsingAjax:{
               is: 'rw',
               init: false,
            },
         },

         //methods
         methods: {

            init: function () {

               var self = this;
               self.getAjaxVar();

            },

            getAjaxVar: function() {

               var self = this;

               //HOW CAN I REFERENCE 'self' THROUGHOUT MY OBJECT?

               $.get('ajax/test.html', function(response) {
                 self.someVarToBeSetUsingAjax = response.value;
               });
            },

            //lots more methods...

         }
    });

   return MyClass;

});

好吧,所以我的问题是-在AJAX函数中,我必须编写var self = this才能使我的对象进入AJAX调用的范围-没问题.但是,我发现自己几乎对类声明中的每个方法都这样做!如何以一种干净有效的方式引用所有方法中的self?我知道您可以通过设置参数在AJAX中使用作用域,假定它不仅是AJAX,而且是其他将作用域封闭到外部的函数.

Ok, so my issue is - in the AJAX function I have to write var self = this to get my object into the scope of the AJAX call - no problem. But, I find myself doing this for almost every single method in my class declaration! How can I reference self in all of the methods in a clean and efficient way? I know you can use scope in AJAX by setting a parameter, assume it's not just AJAX but other functions that close the scope to the outside.

谢谢.

推荐答案

每次嵌套函数时,都必须考虑this.但是,如果您不嵌套一个函数,或者该函数不使用this,则无需考虑它.

Everytime you nest a function, you have to think about this. But if you dont nest a function, or that function doesn't use this you don't need to think about it.

        init: function () {
           var self = this;
           self.getAjaxVar();
        },

因此在这种情况下没有必要.这是完全一样的:

So in this case it's not necessary. This is exactly the same:

        init: function () {
           this.getAjaxVar();
        },

但是在这里:

        getAjaxVar: function() {
           var self = this;

           $.get('ajax/test.html', function(response) {
             self.someVarToBeSetUsingAjax = response.value;
           });
        },

您创建一个内部函数,并且想要引用this的原始值,因此必须将this别名为self,以使其可访问.

You create an inner function, and you want a reference to the original value of this, so you do have to alias this to self to make it accessible.

没有一种方法可以将this固定为类中任何地方的值.

There isn't a way to fix this to a value from everywhere in your class.

也就是说,您确实有一些选择.

That said, you do have some options.

Function.prototype.bind()可以帮助您.

var func = function() { return this.name };
var obj = { name: 'Bob' };
var boundFunc = func.bind(obj);
boundFunc(); // 'Bob'

bind将返回始终将this设置为特定对象的新功能.

bind will return a new function with this always set to a specific object.

所以:

        getAjaxVar: function() {
           $.get('ajax/test.html', function(response) {
             this.someVarToBeSetUsingAjax = response.value;
           }.bind(this));
        },

请注意,并非所有浏览器都支持此功能,对于旧的浏览器,您可能需要使用填充程序.

Note this isn't supported in all browsers, you may need a shim for the old ones.

或者只是习惯self = this.

我也想对coffeescript表示一点点赞,因为它支持运行时不更改上下文的函数声明.

I want to give a minor nod to coffeescript as well, because it supports declaration of functions that dont change the context when run.

obj = {
  name: "bob"
  sayHello: ->
    doSomeAjax({
      success: =>
        alert "successfully made " + this.name + " say hello!"
    })
}

obj.sayHello()

->具有正常功能.但是,粗箭头=>会保留函数内部和外部的this值.在实例方法中的回调中非常方便.当编译为JS时,它基本上会为您做一个self = this别名,每次在内部函数中使用self来引用this.很漂亮.

-> makes a normal function. But the fat arrow => will instead preserve the value of this inside and outside the function. It's very very handy in callbacks within instance methods. When compiled to JS, it basically does a self = this alias for you, using self within the inner function everytime to reference this. It's pretty slick.

不过,在普通的JS中,最常见的模式就是self = this,坚持下去.

In plain JS though, the most common pattern is simply self = this, stick to it.

这篇关于Javascript范围引用外部对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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