oop - How to access JavaScript object properties from a prototype method of the object -
this question has answer here:
i'm not sure how title question, here dilemma. have js object i've encapsulated , inherited methods. 1 of methods inserts anchor tag onclick event pointing 1 of inhereted methods of same object. in second method, run trouble because when user fires click event of anchor tag, "this" keyword anchor element. prevents me accessing properties in object through "this" keyword. here simplified code can see talking about.
<!doctype html> <html> <head> <title>working out issue</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script> function listcontainerviewer(name, readonly) { this.name = name; this.readonly = readonly; } listcontainerviewer.prototype = { constructor: listcontainerviewer, addlistitem: function(itemid, content) { var removebtn = $('<a href="#"><span class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></span> </a>') .clone() .click(this.removelistitem); // here, "this" points listcontainerviewer removebtn.appendto($("#selecteditemlist")); }, removelistitem: function() { if (this.readonly == true) { // how point listcontainerviewer.readonly if points <a>? event.preventdefault(); return; } else { this.remove(); // should point <a> has click event } } } var listcontainer; $(document).ready(function() { listcontainer = new listcontainerviewer('test', true); $('#button').click(function() { listcontainer.addlistitem('12345', 'test content'); }); }); </script> </head> <body> <h1>testing oo js</h1> <a id='button' href='#'>click add</a> <div id="selecteditemlist" style="{width: 800px; height: 400px; background-color: #dddddd}"></div> </body> </html>
so if run code snippet, click add link add anchor tag, notice when click x button anchor, fires removelistitem function, this.readonly not accessible refers anchor tag.
you can use function.prototype.bind
or jquery $.proxy
method setting this
value of function:
.click(this.removelistitem.bind(this));
now in function this
refers instance , not clicked element. getting clicked element can use currenttarget
property of event
object:
removelistitem: function(event) { var element = event.currenttarget; // ... }
note using dom htmlelement.remove
method , not remove
method of jquery object. older browsers not support method. wrapping element jquery constructor , using it's remove
method recommended: $(element).remove();