简体   繁体   English

无法使用此运算符调用javascript函数

[英]unable to call javascript function using this operator

why this operator is not working with this javascript object 为什么此运算符无法与此javascript对象一起使用

var data = {
    opt: null,

    ajaxCall: function () {
        //my ajax call code here

        this.fillDataInDiv(); //This statement is not working
        data.fillDataInDiv(); //this is working why ?
    },

    fillDataInDiv: function () {
        //code to fill data in div
    }
} 

can someone explain, what is the difference between these two statement 有人可以解释一下,这两个语句有什么区别

  1. this.fillDataInDiv(); // and why this statement is not working
  2. data.fillDataInDiv();

The data above behaves more like a namespace, not an object. 上面的data行为更像是名称空间,而不是对象。

Consider this : 考虑一下:

var data = function() {};

var dataObject = new data();

Now if you have to add methods to this class: 现在,如果您必须向此类添加方法:

var data = function() {

    // Equivalent to public members

    this.opt = null;

    // Equivalent to public methods :

    this.ajaxCall = function () {    
        this.fillDataInDiv(); 
    };

    this.fillDataInDiv = function () {
        //code to fill data in div
    };
}

This is depending on the way the ajaxCall be called. 这取决于ajaxCall调用方式。

For simple, it depends on the caller . 为了简单起见,它取决于调用方

If you use data.ajaxCall(); 如果使用data.ajaxCall(); , then yes, this refers to the data . ,那么是的, this是指data

But if the caller is not data , then this refers the caller but not the data . 但是,如果调用方不是data ,则this引用是调用方,而不是data

For example: 例如:

var func = data.ajaxCall;
func(); // this inside data.ajaxCall refers to the window object.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM