Need Help Using John Resigs Simple Javascript Inheritance

John Resigs Simple Javascript Inheritance: http://ejohn.org/blog/simple-javascript-inheritance/

I tried to do such a thing:

var SomeClass = Class.extend({ init: function() { var someFunction = function() { alert(this.someVariable); }; someFunction(); // should alert "someString" }, someVariable: "SomeString" }); var someClass = new SomeClass(); 

This should warn "someString", but this is not because inside the function closing someFunction, the value of this is not a class, it has changed. This does not allow me to access the properties and functions of the class inside the closure function.

Any suggestions?

+4
source share
1 answer

I believe your problem is what "this" means. "this" refers to a function in this case, not an object. You probably want:

 var SomeClass = Class.extend({ init: function() { var self = this; var someFunction = function() { alert(self.someVariable); }; someFunction(); // should alert "someString" }, someVariable: "SomeString" }); var someClass = new SomeClass(); 

VERY LAST CHANGE : See also:

+6
source

Source: https://habr.com/ru/post/1313962/


All Articles