如何在函数中访问创建的对象

How to access a created object in a function

本文关键字:创建 对象 访问 函数      更新时间:2023-09-26

我正在尝试解决以下内容。

我称之为视图:

var loader = new LoadingView();

附加到该视图的函数将创建一个新的对象"微调器"

loader.showLoader()

我现在希望它接下来可以调用一个隐藏该对象微调器的函数

loader.hideLoader();

但是,hideLoader 无权访问"微调器"对象。

为什么?

查看代码:

define([
  'jquery',
  'underscore',
  'backbone',
  'spinner',
], function($, _, Backbone, Spinner){
  var LoadingView = Backbone.View.extend({
       el: '#loader',
       // View constructor
        initialize: function() {
             this.opts = {
              zIndex: 2e9, // The z-index (defaults to 2000000000)
              top: '20', // Top position relative to parent in px
              left: 'auto' // Left position relative to parent in px
            };
            _.bindAll(this, 'showLoader', 'hideLoader');
        },

      showLoader: function () {
        var spinner = new Spinner(this.opts).spin(this.el);
    },
     hideLoader: function () {
         var self = this;
         console.log(self)
      this.spinner.stop();
    }
    }); // end loaderview
return LoadingView;
});

是因为你在局部范围内定义了spinner,它只是showLoader局部范围内的变量,并没有作为你尝试在hideLoader中访问的属性附加到this上下文中,所以尝试将其更改为

 showLoader: function () {
        this.spinner = new Spinner(this.opts).spin(this.el); //assuming spin returns the spinner object itself if not. do the below
        //this.spinner = new Spinner(this.opts);
        //this.spinner.spin(this.el);     
    },
您需要

将微调器对象设置为this的属性:

showLoader: function () {
    this.spinner = new Spinner(this.opts);
    this.spinner.spin(this.el); // not sure if you can chain these calls
},