D
D
danforth2017-03-11 18:05:45
JavaScript
danforth, 2017-03-11 18:05:45

OOP + jQuery, how to do it right?

Tell me, I created a class in JS that will work with discounts (load the number of bonus points via AJAX, then calculate how much it is in money, and process the input where managers will enter the amount to write off bonuses).

It looks like this: pastebin.com/BqqwtPZK

I use the methods of this class as event handlers, the problem is that I pass my own this, and I have to declare some var self = affiliate.
I seem to be confused with this and prototypal OOP, I get the feeling that I'm doing something wrong. How do I change object properties correctly in conjunction with jQuery event handlers?

PS Do not offer all sorts of Vue and Angular, according to the TK, it is jQuery.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Arman, 2017-03-11
@Arik

var self = this;
There is also call(), apply() and bind()

S
Stalker_RED, 2017-03-11
@Stalker_RED

The this keyword in javascript works differently than in other languages.
Unlike PHP, Java, C++, etc., the this value in JavaScript is not statically bound to any object, but depends on the context of the call.
javascript.ru/tutorial/object/thiskeyword
https://learn.javascript.ru/object-methods
https://developer.mozilla.org/en-US/docs/Web/JavaS...
And yes, instead of
var self = affiliate
id: self.customerId
You could just write
id: affiliate.customerId

N
nirvimel, 2017-03-11
@nirvimel

I got the feeling that I was doing something wrong.

Everyone has that feeling when working with JS "classes". And the answer is that in JS the word "class" is called not quite the same (or not at all) as in other programming languages. Therefore, when trying to apply typical OOP approaches to JS "classes", there are always a bunch of small problems. At first glance, all these problems are superficial (as in the transition from one OOP language to another), and only then you realize that everything is much more serious. Classical OOP is simply not applicable here, because there are simply no classes in JS (this understanding comes with time).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question