javascript - How to make the variable available in the methods of the class? -


For this question, I'm just starting to learn JavaScript.

I have 2 ways:

  manager.prototype.filter = function () {var user = []; ... The Manager. Protopp.filter_man = function () {var user = []; ...  

I have to make the property 'user' available for 2 ways (filter, filter_man). So that they can use the shared variable (user) How is it possible to write?

You have a prototype-based legacy

  var manager = function () {this.user = []; } Var Manager = New Manager ();  

These rows will define a manager constructor function and create a new object. What happens when you call new manager () :

  1. A new, empty, object is created: { } .

  2. The code inside the constructor will be the value of this with this new, empty object. Therefore, it will set the user property of an empty array of a new object ( {} ).

  3. New object's __proto __ will be set according to property manager property. Therefore, it happens without looking at you: manager .__ proto__ = manager.prototype .

Then, you want to define new methods on your prototype objects, using inheritance. Keep in mind that the prototype is a plain JS object. Instead of a constructor, an object will be set to the __proto __ property same object in every object created with the manager functions.

Then, you start defining new methods on prototype objects, such as filters function when you, later, manager.filters () Call, he will first see his own property for the filter function and he will not get it. Then, then, it will go for its prototype properties, and if there it will be found there. The manager will run then the filter function, which was defined on the prototype, but by using itself ( manager ) as the reference, This inside the function.

Therefore, to use your user property within the filter function, all you have to do is:

 < Code> manager.prototype.filter = function () {this.user = ...; } The Manager. Protopp.filter_man = function () {this.user = ...; }  

And when you created the object, you can add the same user property.


Comments