I wanted to rearrange my Code to OOP, but I am not able to figure out my errors here, especially since they appear correct according to different Tutorials and examples.
I suppose I misunderstand something of JS´s, object-instantiation and Call stack.
I will provide some examples, which I don´t understand.
What I want here is to do some operations on an Array and then get it to an other class.
https://jsfiddle.net/8g22nj8y/1/
<script>
$(document).ready(function() {
var p = new Parser();
p.init();
p.getArray();
p.getArray2();
p.get3();
}</script>
function Parser() {
var myArray = [];
this.myArray2 = [];
thisReference = this;
this.myArray3=[];
return {
init: function () {
alert("huhu");
this.parse2();
parse();
},
getArray: function () {
alert(thisReference.myArray2.length);
},
getArray2: function () {
alert(myArray);
}
}
function parse() {
var arr = [1, 2, 3];
myArray.push(arr);
myArray2.push(arr);
for(var i =0;i<10;i++){
a=[];
a.push(i);
thisReference.myArray3.push(a);
}
}}Parser.prototype.parse2 = function () {
var arr = [1, 2, 3];
myArray.push(arr);
this.myArray2.push(arr);};
Independent how I run it, it always says that this.parse2() is not a function.
When I am only using parse(), it says that myArray2 is undefined, althought it´s clearly there - just as "class variable". If I change myArray2 in parse() to thisReference.myArray2 it´s working.
Why? I thought an inner Function - which parse() clearly is, is able to grab all the variable in the outer function - in this case Parser(). When I am now using myArray3 either if it´s used with thisReference or with this. "it is not defined".
If I call parse2 with thisReference it´s working, but then "myArray is not defined", yes it´s an local variable but it´s in the same class and if I call parse() I am able to use it without problems.
Furthermore:
simplified: https://jsfiddle.net/Lzaudhxw/1/
function Syntax(){
var mine = new Lex();
myRef=this;
}
Class1.prototype.foo=function(){
myRef.mine.setFunc(5);
myRef.mine.publicFunc();}
function Lex(){
this.x, this.h=1;
return{
publicFunc: function(param){
this.h;
this.x;
},
setFunc: function(x){
this.x=x;
}
}
Initially I set h to be 1. If I now instantiiate Syntax and call from that the publicFunc from Lex both are undefined. But if I run foo() from Syntax and call the publicFunc again, x is set to the value and h is undefined. Why is it not possible to predefine an varriable (in this case h) like that and then use it?
EDIT to Jan´s Answer:
I read in many Tutorials and some production code that you should store "this" into an variable. Why should myRef point to anything else than the Syntax Object? :O
Why is myRef not an variable of Syntax? Does it have to be this.myRef?
Ahh right, var means local, so mine is only accessiable in the constructor?!
I didn´t wanted to init "x", only define it.
Ahh with return{} I am creating a new class/object, then it´s clear that this. does not point to the above vars. But to introduce an myRef=this should do the job, right?
...So, it´s wiser to use prototype to add functions instead of an inner function?
Yeah you've got a bunchload of JS concepts wrong. I suggest you read the documentation. Tried adding a few explanations.
function Syntax(){
// Since you're returning a new object from "Lex" straight away, there's
// little point of using "new" here
var mine = new Lex();
// Why store "this" here? "this" will be accessible from your prototype
// methods pointing to your object instance... Provided you use "new Syntax()",
// Otherwise "myRef" will (probably) point to the global object.
myRef=this;
}
// Where's "Class1"? You don't have a Class1 function anywhere. You probably mean "Syntax"
Class1.prototype.foo=function() {
// "myRef" is not a property of "Syntax", so it wouldn't be accessible here.
// Furthermore, "mine" is declared as a variable above, so it wouldn't be
// accessible in this manner even if "myRef" pointed to "this" (which it doesn't).
myRef.mine.setFunc(5);
myRef.mine.publicFunc();
}
function Lex(){
// This is a correct property declaration of h. You're not setting the
// value of x here though, just calling it. Javascript allows "trying"
// to call ANY property of ANY object without giving neither a compilation
// nor runtime error, so calling the undefined "this.x" here is valid.
// It just won't do anything.
this.x, this.h=1;
// Here you return a new object straight off, so the below "this" will point
// to the object below, not the "Lex" object defined above. So your above
// defined "this.h" will not be used, it's a property of a different object.
return {
publicFunc: function(param){
this.h;
this.x;
},
setFunc: function(x){
this.x=x;
}
}
// You're missing a closing bracket here.
What you're probably trying to do would look something like this with correct Javascript syntax
function Syntax(){
this.mine = Lex();
}
Syntax.prototype.foo=function() {
this.mine.setFunc(5);
this.mine.publicFunc();
}
function Lex() {
return {
h:1,
publicFunc: function(){
console.log(this.h);
console.log(this.x);
},
setFunc: function(x){
this.x=x;
}
}
}
var s = new Syntax();
s.foo();
But returning an object from Lex would be pretty impractical in most cases. So what you really REALLY want to do is probably
function Syntax(){
this.mine = new Lex();
}
Syntax.prototype.foo = function() {
this.mine.setFunc(5);
this.mine.publicFunc();
}
function Lex() {
this.h = 1;
}
Lex.prototype = {
publicFunc: function(){
console.log(this.h);
console.log(this.x);
},
setFunc: function(x){
this.x=x;
}
};
var s = new Syntax();
s.foo();
Related
I am trying to access settings and values/functions from within other functions in JavaScript, and believe there is probably a simple rule which I am missing. Here is a very simplified code example:
function h(){
// example settings I want to declare for h()
this.settings = {
critical: 400,
readCritical: function(){
return this.settings.critical; // /!\ but this does not work
}
}
this.hsub = function(){
return this.settings.critical; // /!\ this does not work either
}
}
var x = new h();
console.log(x.settings.critical); // This works fine
console.log(x.settings.readCritical()); // I can *call* this fine, but it can't read outside itself
console.log(x.hsub()); // I can also call this but same problem
console.log(h.settings); // `undefined`; I understand I can't see directly into the function
You can see the this.settings.critical value, which I'm trying to access from inside the respective functions readCritical and hsub. How can I do this? Specifically from the instantiated x.
Also a secondary question but related, I would prefer to declare var settings = {} instead of this.settings. Is this possible or preferable?
Only change you need to make is to remove .settings from within the readCritical function.
The hsub works as is. Not sure why you thought there was a problem
function h(){
this.settings = {
critical: 400,
readCritical: function(){
return this.critical; // reference `critical` directly
}
}
this.hsub = function(){
return this.settings.critical; // this works just fine
}
}
var x = new h();
console.log(x.settings.critical); // 400
console.log(x.settings.readCritical()); // 400
console.log(x.hsub()); // 400
// This is expected to be `undefined`
console.log(h.settings);
Ahh, another old classic closure problem.
There are two ways to solve it:
function h(){
var self = this;
this.settings = {
critical: 400;
readCritical: function() {
return self.settings.critical(); // otherwise this.settings will 'cover' `this`.
}
}
}
readCritical: () => this.settings.critical(); // arrow functions won't form a function scope
The scope of this (and binding functions to set it) are much discussed topics in JS. However, you seem not to be looking for this specifically, but sharing variables, there's another alternative. All in all, there's no best answer, but since you would also like to declare var settings = {}: you actually can and have access to that local variable available inside the other functions.
function h(){
var settings = { //var settings is a local variable of the function h (or instance of it). If ES6 is allowed 'let' or 'const' are preferrable
critical: 400,
readCritical: function(){
return settings.critical;
}
};
this.settings = settings; //this.settings is not the same variable as var settings, making this statement valid
this.hsub = function(){
return settings.critical; //the local (var) settings is used
}
}
var x = new h();
console.log(x.settings.critical);
console.log(x.settings.readCritical());
console.log(x.hsub());
Pitfall here, is that if the calling code changes x.settings to something else, the variables will not point to the same instance (if they change a value inside x.settings, all is well). If that is a risk, it could be exposed as a property method instead
It looks like you only want to have one instance. If that is so, then just create the instance immediately with an object literal notation:
var h = {
settings: {
critical: 400,
readCritical: function(){
return this.critical;
}
},
hsub: function(){
return this.settings.critical;
}
}
console.log(h.settings.critical);
console.log(h.settings.readCritical());
console.log(h.hsub());
console.log(h.settings);
Now all four property accesses work as expected when given the singleton object h.
I just learned OOP and there is one little thing that I am not able to solve. The problem is a scope issue of some sort.
If I create a new object then how will I be able to give it access to my constructor function if the constructor function is inside another function? Right now I get undefined. Storing the function in a global variable wont do the job.
var example = new something x(parameter);
example.i();
var getFunction;
var onResize = function() {
getFunction = function something(parameter) {
this.i= (function parameter() {
// Does something
});
};
};
window.addEventListener('resize', onResize);
onResize();
For OOP javascript, the pattern should be like this.
//defining your 'class', class in quotes since everything is just functions, objects, primitives, and the special null values in JS
var Foo = function (options) {
// code in here will be ran when you call 'new', think of this as the constructor.
//private function
var doSomething = function () {
}
//public function
this.doSomethingElse = function () {
}
};
//actual instantiation of your object, the 'new' keyword runs the function and essentially returns 'this' within the function at the end
var foo = new Foo(
{
//options here
}
)
If I understand you, you want to know how to access variables inside another function. Your attempt is reasonable, but note that getFunction is not bound until after onResize is called. Here's a bit of a cleaner demo:
var x;
function y() {
// The value is not bound until y is called.
x = function(z) {
console.log(z);
}
}
y();
x('hello');
A common JavaScript pattern is to return an object that represents the API of a function. For example:
function Y() {
var x = function(z) {
console.log(z);
}
return {
x: x
};
}
var y = Y();
y.x('hello');
You should definitely read up on the basic concepts of JavaScript. Your code and terminology are both sloppy. I'd recommend Secrets of the JavaScript Ninja. It does a good job explaining scope and functions, two tricky topics in JavaScript.
I am trying to understand better the use of that and this in JavaScript. I am following Douglas Crockford's tutorial here: http://javascript.crockford.com/private.html
but I am confused regarding a couple of things. I have given an example below, and I would like to know if I am making a correct use of them:
function ObjectC()
{
//...
}
function ObjectA(givenB)
{
ObjectC.call(this); //is the use of this correct here or do we need that?
var aa = givenB;
var that = this;
function myA ()
{
that.getA(); //is the use of that correct or do we need this?
}
this.getA = function() //is the use of this correct?
{
console.log("ObjectA");
};
}
function ObjectB()
{
var that = this;
var bb = new ObjectA(that); //is the use of that correct or do we need this?
this.getB = function()
{
return bb;
};
that.getB(); //is the use of that correct or do we need this?
}
Note this is just an example.
this in JavaScript always refers to current object, method of which was called. But sometimes you need to access this of your object in deeper. For example, in callbacks. Like so:
function MyClass() {
this.a = 10;
this.do = function() {
http.get('blablabla', function(data) {
this.a = data.new_a;
});
};
}
It will not work, because this in callback may refer to http, to some dom element or just window(which is really common). So, it is common solution to define self or that, an alias for this or your object, so you can refer it anywhere inside.
function MyClass() {
var self = this;
this.a = 10;
this.do = function() {
http.get('blablabla', function(data) {
self.a = data.new_a;
});
};
}
This should give you vision why it is used and how it should be used.
There is no other reasons(currect me if I'm wrong) to create special variable, you can use this to send your object to other objects and do things, many assignments, such logic, wow...
ObjectC.call(this); //is the use of this correct here or do we need that?
The first thing you need to understand is how the this keyword works. It's value depends on how the function/method/constructor is called.
In this case, function ObjectA is a constructor, so you can just use this inside the code of it. In fact, with var that = this; you declare them to be absolutely identical (unless you use that before assigning to it).
function myA() {
that.getA(); //is the use of that correct or do we need this?
}
Again, it depends on how the function is called - which you unfortunately have not show us. If if was a method of the instance, this would have been fine; but but it seems you will need to use that.
this.getA = function() //is the use of this correct?
As stated above, using that would not make any difference.
var bb = new ObjectA(that) //is the use of that correct or do we need this?
var that = this;
that is undefined when it is used here. And it would be supposed to have the same value as this anyway. Better use this.
that.getB(); //is the use of that correct or do we need this?
Again, both have the same effect. But since you don't need that, you should just use this.
Everything is correct except for :
function ObjectB()
{
var bb = new ObjectA(that) //this is wrong
var that = this;
this.getB = function()
{
return bb;
};
that.getB();
}
You are missing ; and that isn't declare.
You need that (in your case, this is the variable name you use) when you want to use this in another scope :
function ObjectB()
{
var that = this;
// here 'this' is good
function()
{
// Here 'this' doesn't refer to the 'this' you use in function ObjectB()
// It's not the same scope
// You'll need to use 'that' (any variable from the ObjectB function that refers to 'this')
};
// Here 'that' = 'this', so there is no difference in using one or another
}
What "that" is in this context is simply a variable that is equal to "this". That means saying "that" is exactly the same as saying "this", which makes in unnecessarily complicating.
This code:
var that=this;
that.getA();
Will yield the same result as this code:
this.getA();
Having a variable to represent "this" just complicates things when you can just say "this".
I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.
Firstly, "JavaScript OOP - the smart way" at http://amix.dk/blog/viewEntry/19038
See the implementation section:
var parent = new this('no_init');
And also "Simple JavaScript Inheritance" on John Resig's great blog.
var prototype = new this();
What does new this(); actually mean?
This statement makes no sense to me because my understand has been that this points to an object and not a constructor function. I've also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.
My head has gone off into a complete spin.
Could someone please explain this in detail?
In a javascript static function, you can call new this() like so,
var Class = function(){}; // constructor
Class.foo = function(){return this;} // will return the Class function which is also an object
Therefore,
Class.foo = function(){ return new this();} // Will invoke the global Class func as a constructor
This way you get a static factory method. The moral of the story is, not to forget functions are just like any other objects when you are not calling them.
What is confusing you, I think, is just where "this" is really coming from. So bear with me-- here is a very brief explanation that I hope will make it quite clear.
In JavaScript, what "this" refers to within a function is always determined at the time the function is called. When you do:
jimmy.nap();
The nap function (method) runs and receives jimmy as "this".
What objects have references to nap is irrelevant. For example:
var jimmy = {}, billy = {};
jimmy.nap = function(){ alert("zzz"); };
var jimmy_nap = jimmy.nap;
jimmy_nap(); // during this function's execution, this is *NOT* jimmy!
// it is the global object ("window" in browsers), which is given as the
// context ("this") to all functions which are not given another context.
billy.sleep = jimmy.nap;
billy.sleep(); // during this function's excution, this is billy, *NOT* jimmy
jimmy.nap(); //okay, this time, this is jimmy!
In other words, whenever you have:
var some_func = function(arg1, arg2){ /*....*/ };
// let's say obj and other_obj are some objects that came from somewhere or another
obj.some_meth = some_func;
other_obj.some_meth = some_func;
obj.some_meth(2, 3);
other_obj.some_meth(2, 3);
What it's getting "translated" into (not literally-- this is pedagogical, not about how javascript interpreters actually work at all) is something like:
var some_func = function(this, arg1, arg2){ /* ...*/ };
// let's say obj and other_obj are some objects that came from somewhere or another
obj.some_meth = some_func;
other_obj.some_meth = some_func;
obj.some_meth(obj, 2, 3);
other_obj.some_meth(other_obj, 2, 3);
So, notice how extend is used in the example on that page:
UniversityPerson = Person.extend({ /* ... */ });
Pop quiz: When extend runs, what does it think "this" refers to?
Answer: That's right. "Person".
So the puzzling code above really is the same as (in that particular case):
var prototype = new Person('no_init');
Not so mysterious anymore, eh? This is possible because unlike in some languages,
a JavaScript variable-- including "this"-- can hold any value, including a function such as Person.
(There is nothing that makes Person specifically a constructor. Any function can be invoked with the new keyword. If I recall the exact semantics, I think they are that when a function is called with the new keyword, it is automatically given an empty object ({}) as its context ("this") and when the function returns, the return value is that same object unless (maybe?) the function returns something else)
This is a cool question because it speaks to a pretty essential part of JavaScript's neatness or oddness (depending on how you see it).
Does that answer your question? I can clarify if necessary.
AJS.Class effectively* translates this:
var Person = new AJS.Class({
init: function(name) {
this.name = name;
Person.count++;
},
getName: function() {
return this.name;
}
});
Person.count = 0;
into this:
var Person = function (name) {
this.name = name;
Person.count++;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
Person.extend = AJS.Class.prototype.extend;
Person.implement = AJS.Class.prototype.implement;
Person.count = 0;
Therefore, in this case, this in AJS.Class.prototype.extend refers to Person, because:
Person.extend(...);
// is the same as
Person.extend.call(Person, ...);
// is the same as
AJS.Class.prototype.extend.call(Person, ...);
* There are a lot of cases I don't go over; this rewrite is for simplicity in understanding the problem.
Imagine the following situation :
var inner = function () {
var obj = new this;
console.log(obj.myProperty);
};
var f1 = function () {
this.myProperty = "my Property"
}
f1.f2 = inner;
f1.f2();
Here the calling object is itself a function, so this will return a function, and we can instantiate it.
In order to use this()(not this) the outer function(the context) must itself return smth that can be instantiated(another function):
var inner = function () {
var obj = new this();
console.log(obj.myProperty);
};
var f1 = function () {
var func = function () {};
func.myProperty = 'my property';
return func;
};
f1.f2 = inner;
f1.f2();
A simpler code explaination:
class User {
constructor() {
this.name = '';
this.age = '';
}
static getInfo() {
let user = new this();
console.log(user);
}
}
User.getInfo()
Output:
Object {
age: "",
name: ""
}
see this link http://www.quirksmode.org/js/this.html It will tell you about the this keyword, but I am not sure what this() is, may be its some kind of user defined function...... that you are not aware of...
"this" means the context of the function currently running.
The code you are posting surely appears in a function that act as a method for an object.
So the object is the context of the function.
"new this()" will return a clone of the current object after running its constructor function with the passed arguments.
this() refers to the the function that the code is in, but this() would have to be within that function. Calling new this(); within a function would create a never ending loop. Calling it outside of a function would be redundant because there is no function/class set as this().
Please see the following script:
var x = function(param){
this.data=param;
this.y = function(){
alert(this.data)
}
return this;
}
/*
x.prototype.z = function(){
alert(this.data);
}
*/
x(123).y();
x(123).z(); // This should behave same as y()
When I call x(123).y() then message displays 123. The function y() declared inside x()
Now I want to declare another function z() which will reside outside x() but will behave same as y() [associate with x()]
Is it possible? If possible how?
You're missing a new when calling x(). Otherwise, this within the function body will refer to the global object (window in browser contexts) and not an instance of x.
That's the reason why calling z() (after un-commenting the code) doesn't work. Calling y() only works by coincidence as you create a global variable data, whose value will be overwritten by the next call to x().
I have no idea what you're trying to accomplish, and from what I can see, it most likely isn't a good idea. Anyway, here's an example of how to get rid of explicit new when creating objects:
var x = function(param){
// add missing `new`:
if(!(this instanceof x))
return new x(param);
this.data=param;
this.y = function(){
alert(this.data)
}
}
x.prototype.z = function(){
alert(this.data);
}
x(123).y();
x(456).z();
It is possible, and your commented-out z function should work as is if you fix how you're creating xs.
Note that your function y doesn't have to be declared inside the constructor if it's only dealing with instance properties (which in your code it is), and doing so has a significant memory cost (every instance gets its own copy of that function). You only want to do that if you absolutely have to for major data hiding reasons, given the costs involved.
Edit: Sorry, I missed something: You're missing the new keyword, your examples should be:
new x(123).y();
new x(123).z();
...and your constructor shouldn't return this.
Complete example:
var x = function(param) {
this.data=param;
// Doesn't have to be in the constructor, and you should
// avoid it unless you're doing something with major
// data hiding a'la Crockford
this.y = function() {
alert(this.data)
}
}
x.prototype.z = function() {
alert(this.data);
}
new x(123).y();
new x(123).z();
This is the Crockford article I mention above, but again, it has big memory implications.
function generator( param ) {
this.data = param;
this.y = function() {
alert( this.data )
}
}
generator.prototype.z = function() {
alert( this.data );
}
x = new generator( 3 );
x.y()
x.z()
Not sure if this is what you want, but this is a constructor named generator which returns an object, and a prototypal method is defined outside of it with the new keyword.
As others stated:
you don't need to return this in the constructor
you call it with the new keyword
all methods declared with this are public unless you use var in which case they become private