javascript - How to make the variable available in the methods of the class? -
javascript - How to make the variable available in the methods of the class? -
i apologize question, starting larn javascript.
i have 2 methods:
manager.prototype.filters = function () { var user = []; ... manager.prototype.filters_main = function () { var user = []; ...
i need create property 'user' available 2 methods (filters, filters_main). can utilize shared variable (user). how possible write?
you have understand prototype-based inheritance here.
var manager = function() { this.user = []; } var manager = new manager();
these lines define manager
constructor function , create new object. when phone call new manager()
, happens is:
a new, empty, object created: {}
.
the code within constructor run new, empty, object beingness value of this
. so, set user
property of new object ({}
) empty array.
the __proto__
property of new object set value of manager.prototype. so, happens without seeing: manager.__proto__ = manager.prototype
.
then, want define new methods on prototype objects, using inheritance. maintain in mind prototype plain js object. not constructor, object. every object created manager
function have __proto__
property set the same object.
then, start defining new methods on prototype object, filters
function. when you, later, phone call manager.filters()
, first own properties filters
function , won't find it. so, then, go prototype properties, , there if find it. manager
run filters
function defined on prototype, using (manager
) context, this
within function.
so, utilize user
property within filters
function, have is:
manager.prototype.filters = function () { this.user = ...; } manager.prototype.filters_main = function () { this.user = ...; }
and you'll manipulating same user
property defined when object constructed.
javascript
Comments
Post a Comment