Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE throws an exception on "self = this" in JavaScript?

I have some objected oriented JS that works fine in firefox but not in IE 8 (though it will be IE 9 that we will need to support).

When I do: "self = this;" IE flags that as an error. I am trying to set this to self to then use it in a jquery callback to call some other
method in my JS object.

this.upd_params = function () {
   $("#add-parameter-modal").modal('hide');

   var param_form = $('#add_param_form');
   self = this;
   this.added_params = [];
   this.removed_params = [];

   $('.unused_parameter').each(function (index, obj) {
     if (obj.checked) {
       id = self.get_idnum(obj.id);
       self.add_param2list(id);
     }
   });


   $('.used_parameter').each(function (index, obj) {
     if (!obj.checked) {
       id = self.get_idnum(obj.id);
       self.remove_param(id);
     }
   });

   this.upd_html();

   cfg_form_changed = true;

};
like image 368
user1456508 Avatar asked Aug 17 '12 21:08

user1456508


People also ask

Is self the same as this in JavaScript?

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.

Can you use self in JavaScript?

You might sometimes use self to capture the context of this before it is destroyed by some function. Unfortunately self is also an alias for window , the global top-level object.

Does JavaScript have this?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword.

What is the use of this in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


1 Answers

Make sure self is a locally-scoped (not global) variable.

var self = this;

Otherwise, self refers to window.self and assigning to it is not allowed.

like image 110
ephemient Avatar answered Nov 12 '22 00:11

ephemient