...

View Full Version : OOP JavaScript



Code Wizard
02-11-2004, 09:19 PM
Please tell me a few good situations were the OO approach is the best techinque to use...

liorean
02-11-2004, 09:36 PM
Writing APIs, libraries or code that is large enough to require management, when you want to create distinct separate modules or packages that are largely independent of eachother. Object based function driven coding is often a far better choice in JavaScript - it's smaller and more efficient, but the code stays clearly ordered and code snippets are still largely independent of eachother.

Or when you write code for others to use, so that there is no need for them to actually get a knowledge of the code. (Functional style can do this as well)

Also remember that for JavaScript, the deep hierarchical inheritance trees you see in C++ or Java are far less useful than a flatter, more shallow structure. JavaScript has rather strong object orientation, but for the uses JavaScript is being put to object orientation is often not the best way to go.

Garadon
02-11-2004, 09:38 PM
I would say OO scripts is always the best.

1. it incapsulates its abilities.
2. it make clutter 10-100 global variables.

This is very usefull make it easy to use ones javascript in combination with others, since you have only taken up 1 global name, instead of 1 for each function and variable.

liorean
02-11-2004, 09:43 PM
Garadon: But for those purposes object orientation is overkill. There's no need at all for inheritance, and I'd say an object based system is much better suited. Have a look at my cookies library for instance: <http://liorean.web-graphics.com/scripts/cookie.zip>

That code would only have been longer and harder to read had I made it object oriented instead of plainly object based, and I still use only one global variable for it.

RadarBob
02-12-2004, 06:01 AM
I also have to say using OO techniques is *always* a good thing to do. My explaination won't make much sense unless you've "been there, done that" but when i was learning JavaScript OO stuff I kept going on faith that there would be a payoff; and there was.

Object Think
Generally i think about my problem solutions in terms of objects, and the code naturally comes out that way. It is a bit different way to approach a problem; having been brought up in the traditional procedural coding style I can tell the difference.

OO code tends to be more complete. When I design my objects I tend to come up with utility functions. For example I write a toString() function to output my object's property values. Really good for troubleshooting and it's there for the next guy if he needs it.

OO code tends to be more organized. Instead of a mass of variables I group them where it makes sense and make objects and even sub-objects. This organization tends to pay off later when I'm referenceing things all over the place. Data is easily passed "in chunks" because it's all one object.

When I am thinking about this object and what IT should do I tend to write more rigorous validation code; due to OO principles such as "always keep an object in a valid state."

OO think makes you a better programmer
A lot of what goes into good object code writing is just good coding practices period. I think "my object must do A, B, and C so I write methods that do A (and nothing else), B (and nothing else), and C (and nothing else). There you just applied the principle of "maximize cohesion and minimize coupling". Miraculously this makes code easier to read, easier to modify, easier to test.

OK, you do write more code
I find this to be true. This is a natural consequence of writing better, more robust code, but it goes against the grain of web programmers. I think we get brainwashed into thinking we must write the absolute minimum code in order to "save bandwidth." Talk about your urban myths! I write so much client-side JS that fellow programmers give me "that look" (really, they do!). But no one has yet proven the down side. In the mean time I've got solid code! Can't argue w/ success.

OO code is often easier to write
When your data is organized into objects, and the functions that go with it are each "singular in purpose" (remember "maximize cohesion" above?); I've often found that the methods I write are pretty small. Oh I might have a lot of methods, but they tend to be smaller and/or less complex.

Again we get into the "less code is better" bass-ackwards way of thinking issue. "I'll save some keystrokes by putting 3 things into one function - that's good". NOT!! Writing smaller, more focused - singular in purpose - makes each function much less complex, thus easier to write, debug, read, etc.

OO code is a little more reusable
Variables and methods are encapsulated w/in the object so if you include the code in an HTML page, you don't get variable name conflicts.

A well written object stands alone. It has all the methods it needs to do what it does. These methods do what they say they do and nothing more. A well written object tends to not need more code written for it for the next time it's used.

OO code is easier to use
After we invoke the buzzwords encapsulation and abstraction we admit to ourselves that at some point we do have to write down-and-dirty detail code OF the object. BUT once that's done the magic happens. You will pleasantly discover that writing the code using the object looks and feels "higher level" than you'd expect.

Because you wrote and debugged the core object code first you find yourself focusing on the highlevel control code rather than getting distracted by trying to write and debug high level and detail code all at the same time.

After some practice with this stuff you begin to notice some things:
* your code is more modular because you wrote it "from the ground up".
* You loose the "I'm trying to write all the code all at once" feeling.
* You surprise yourself one day realizing you wrote perhaps your most complex code yet, but it works!
* Testing is easier
* You can tell you're putting out consistantly better quality code.

Garadon
02-12-2004, 08:30 AM
read liorean code, and if you call that easy to read ur mad in IMHO :), I strongly assume that script is optimised with minimising white spaces and new lines after u coded it :).

Oh and inheritance I didn't know u could that how u do that in Javascripts?

liorean
02-12-2004, 02:17 PM
Garadon: Yes, the comments, spaces and indentations are removed, and I also don't close inherently closed statements by a semicolon. However, if you put those back in place you will find the code much more easy to read than it's object oriented equivalent is.

As for inheritance have a look at the JavaScript ref sticky, the object orientation section.




RadarBob: A typical procedural/imperative view, I'd say. Let me compare to the object based and functional ways of doing things:

First on all, the difference between object based and object oriented coding: One uses objects, the other uses objects with inheritance. Inheritance requires objects and instances and setting prototypes, while object based programming just requires the use of objects for storage, which object oriented programming requires as well.

Second, the functional versus imperative views: The functional view see everything as programs calling other programs, which in the end complete a task. The imperative see everything as a sequence of commands that in the end complete a task. The functional way is task oriented, the imperative way is processing oriented. Functional programming typically use scoping, closures and what is in imperative thinking called callback functions, while imperative uses statements and structures.

Object think
In object based programming, you use object for storage and performing actions. You use properties and methods in the same way as with object oriented code, but you don't utilise inheritance where it is not needed. Functions may either be part of an object as methods, which means the object is performing things. Or they may be functions taking an object for argument, and handling that object.

Function, scope, think
In functional programming functions handle data, and are in turn data themselves. Scoping provides encapsulation and closures provides privacy - so called black boxes are provided by closures, the same way object do in imperative languages. Object privacy is provided by closures, too.

Task orientation makes you a better programmer
Or, for every task the tools best equiped for the purpose. Use object orientation only if inheritance is a feature you need. Use object based programming if you only need objects as containers and abstractions related to the task. And use methods or functions depending on whether it it the object that should be doing things or things should be done with the object. Separate tasks into functions or methods of their own for easier testing, extending and modification, as well as making the code easier to read.

For each langauge a suitable abstraction
Don't think the best tools for the task are the same across langauges. JavaScript has modular, dynamic objects that are best suited for shallow inheritance trees, while for example Java has fixed, static objects that are best suited for deep inheritance trees.

Readability
Object oriented code is larger than procedureal or flat imperative code, true. It is also better structured and task separated. Functional programming is also task separated, to an even higher degree than imperative object oriented code, and object based code provides the same structural advantages as object oriented code. Which in the end means that functional and object based code is more readable and better task separated than regular object oriented code.

Reusability
Is one of the the key concepts of functional programming. The scoping and closures creation together with task orientation makes the code widely reusable because of the task separation. Scoping provides the solution to the namespace problem.

Ease of use
Task orientation makes functional code easy to use on the same way object orientation does - by task separation. The difference lies in that while object oriented code is object centered, the functional code is task centered. This makes functional code better for the purposes of achieveing a single, simple goal, or a complex task consisting of several such single, simple goals. Object orientation is better for heavy structures and data storage, but not for performing tasks.

Things you notice if you use functional, object based programming
- Your code is readable.
- Your code is modular.
- Your code is task instead of structure separated.
- Black boxes.
- Testing is easy and can be done on single instances.



A simple comparison, object based versus object oriented:


// Object based
var
YourObject={
toString:function(){/*blah*/},
property:'value',
method:function(value){
this.property=value;
}
};
YourObject.method('argument');

// Object oriented
function YourObjectConstructor(value){
this.toString=function(){/*blah*/};
this.property=(value!=undefined)?
value:
'value';
this.method=function(value){
this.property=value;
};
}

var
YourObject=new YourObjectConstructor('argument');

mordred
02-12-2004, 02:33 PM
EDIT: Post crossed, this one was written before the last replay of liorean.

Wow RadarBob, what an essay. I remember dimly that we engaged in OOP discussions some months ago. Nice to see that you reap now the benefits of venturing into OOPtupia. :)

Let me state that I fully agree to what you wrote, I've had a similar experience. The points about cohesion and coupling - very good you mentioned them. A week ago I had to customize a very complex interactive calendar script - and I was very successful because the whole script was object-oriented. I even reused some components in another script, to the calendar unrelated, running on the same page.

Code Wizard, don't get intimidated if people tell you that OOP takes longer to write and is less efficient. The efficiency issue pops *always* up in the discussion whether or not to use OOP, and has been debated to death. Usually it is countered by telling that you should optimize later after you've done some benchmarking and identified the parts of code that have to run more efficiently.

OOP doesn't take longer to write. It takes longer to define the interfaces of your objects, and the relation between them. Which objects sends which message to whom and questions like that. But once you've done this, you have very good idea of the problem space. That's the main difference between OOP and procedural programming: In the latter, you have to use the computer's way to think and model your problem in it. In OOP, you define the problem in your own vocabulary. *That* improves readability, and makes your app better to understand by others.

liorean, I don't know why you brought up inheritance. You don't need to use inheritance if you have better, more fitting alternatives, and yet your app may qualify as a true OOP app nevertheless. Often, inheritance is overused and better refactored as composition/aggregation. Remember that inheritance breaks encapsulation.
Also, I have to agree with garadon that your cookie library is not a very good example for improved readability through an object-based approach. It's nice, condensed, and probably a bandwidth save, but another developer could have written a CookieJar library in which each cookie is modeled as a separate object, and it would be still efficient to use. Some people favor sometimes features over slight margins in performance.

RadarBob
02-12-2004, 02:36 PM
Originally posted by Garadon
read liorean code, and if you call that easy to read ur mad in IMHO :), I strongly assume that script is optimised with minimising white spaces and new lines after u coded it :).

Oh and inheritance I didn't know u could that how u do that in Javascripts?
"Make things as simple as possible, but no simpler"
Albert Einstein

I don't grock the syntax/style used by liorean either. But basic OO scripting w/ JS is not that esoteric. Nonetheless this supports my points. This detail code may look daunting, but USING it is quite another matter.

As for inheritance, that's a bit funky in JS. JS is NOT an Object Oriented language, it's "object based." The distinction is that features that make a language OO are not there or are weakly supported in JavaScript. Inheritance and polymorphism are the two classic features of OO, but are not "fully there" in JS, IMHO.

In fact I've been writing JS for over a year w/out using inheritance - because I didn't know how to do it. You simply won't find it discussed in virtually any published material. At times I wish I had it, but I managed. Just recently I've "seen the light". Search this forum for a recent thread; look for "closure" or "closures". That'll make your head swim...

Getting back to fundamentals... The basics of 'object based' scripting w/ JS gives you the basic encapsulation and nicely organized data / code. That's one giant leap. Get that down pat first.

Forcing(?) rigorous OO capabilities in JS is yet another giant leap. But as I understand it the basics of inheritance means utiizing the "prototype" property that every object (built-in and "home grown") has. You know that if you define a new method, for example "Array.prototype.MyFancyArrayFunction" that the "MyFancyArrayFunction" is "inherited" - is automatically available for use by every Array object. Follow the links from that thread I mentioned above, you find at least some of what you're looking for.

IMHO if we *really* need to have serious OO capabilities in web-slinging, we need to drop the "script" in "javascript", if you know what I mean.

liorean
02-12-2004, 03:57 PM
As for inheritance, that's a bit funky in JS. JS is NOT an Object Oriented language, it's "object based." The distinction is that features that make a language OO are not there or are weakly supported in JavaScript. Inheritance and polymorphism are the two classic features of OO, but are not "fully there" in JS, IMHO.
I beg to differ on that point. JavaScript is a full fledge object oriented language that supports polymorphism. It's a prototype based inheritance, true, but it is an object oriented one. Object orientation is achieved by making the constructor functions (that are also objects) act as initiators for object instances created by using the new keyword. The prototype acts as the template for the object instances in the same way classes do in the classical inheritance model. Destructors are unnecessary as the garbage collection mechanism does that. Object instances and prototypes are not fixed, which means that in many cases adding a property or method is more effective than creating a subclass, thus the flatter object inheritance trees. Polymorphism is achieved by dynamic prototype or method overriding in instances and by scoping, but makes less of a difference since JavaScript is a dynamically typed language and you use run time object type detection coupled with forking instead of overloading functions and methods.

In fact I've been writing JS for over a year w/out using inheritance - because I didn't know how to do it. You simply won't find it discussed in virtually any published material. At times I wish I had it, but I managed. Just recently I've "seen the light". Search this forum for a recent thread; look for "closure" or "closures". That'll make your head swim...

Getting back to fundamentals... The basics of 'object based' scripting w/ JS gives you the basic encapsulation and nicely organized data / code. That's one giant leap. Get that down pat first.

Forcing(?) rigorous OO capabilities in JS is yet another giant leap. But as I understand it the basics of inheritance means utiizing the "prototype" property that every object (built-in and "home grown") has. You know that if you define a new method, for example "Array.prototype.MyFancyArrayFunction" that the "MyFancyArrayFunction" is "inherited" - is automatically available for use by every Array object. Follow the links from that thread I mentioned above, you find at least some of what you're looking for.

IMHO if we *really* need to have serious OO capabilities in web-slinging, we need to drop the "script" in "javascript", if you know what I mean. [/B]They are both object oriented. Java has a more complete system bewcause it has parameters that allow super/sub refrencing, but that is something that could be added to JavaScript easily, had ECMA chosen to go that way. (They didn't. They change to Class based inheritance in the fourth revision, currently being written.) The prototype object allows single object inheritance, and together with JavaScript's dynamic typing and inheritance, it allows a more modular inheritance model than that Java has.

Roy Sinclair
02-12-2004, 05:48 PM
Back to the original question, here's a good example of why OOP is a good thing to do. Suppose you've coded a widget for a web page using normal coding methods. Later on you decide you need two widgets on the page so now you have to create a second copy of your code using unique variable and function names. Then it becomes obvious that four widgets would be even better, guess what your going to have to do now :( .

However, if you coded the first widget using OOP methods then all subsequent uses would require nothing more than an additional invocation of the created object.

Code Wizard
02-14-2004, 10:02 PM
Originally posted by Roy Sinclair
Back to the original question, here's a good example of why OOP is a good thing to do. Suppose you've coded a widget for a web page using normal coding methods. Later on you decide you need two widgets on the page so now you have to create a second copy of your code using unique variable and function names. Then it becomes obvious that four widgets would be even better, guess what your going to have to do now :( .

However, if you coded the first widget using OOP methods then all subsequent uses would require nothing more than an additional invocation of the created object.

What's a wiget...?
:p

JAVAEOC
02-15-2004, 12:48 AM
where can i learn OO ?

liorean
02-15-2004, 12:56 AM
Have a look under the object orientation part of my JavaScript Refs sticky. Devedge's JavaScript 1.5 Core Guide also has a pretty good piece on it in chapters seven and eight.

JAVAEOC
02-15-2004, 01:20 AM
cool
thanks alot....


but why use prototype?

why couldnt i just chage the falue like this

obj1.name="ahhh"
then chage to:
obj1.name="lol"

why cant i do it that way? (its easier to me:))

JAVAEOC
02-15-2004, 01:30 AM
why wont this work?
watch('cat1.name', cat1.talk())

Code Wizard
02-15-2004, 09:29 PM
When prototyping all instances of the object will share that property/methd u add/change,but if u change a prop/method for an object instance,only that instance is affected...

beetle
02-15-2004, 10:14 PM
Javascript inheritance is both clunky and rarely useful. I've written lots and lots of OOP javascript, and I agree with mordred: composition and aggregation are much more useful facilities of OO when talking javascript. I'm not saying JS inheritence is never right, I'm just saying it very rarely is. The types of tasks we use Javascript for just don't need it.

I think one of the biggest benefits that OO JS offers has been mentioned, but not highlighted yet by this thread: multiple instances.

Just search around - you're bound to find many people having problems trying to "run the same script more than once on the same page". Since coding objects provides encapsulation, we can instantiate as many instances as we like of the same script, not to mention the benefits when running multiple scripts of various natures simultaneously..

liorean
02-16-2004, 12:49 AM
Originally posted by mordred
liorean, I don't know why you brought up inheritance. You don't need to use inheritance if you have better, more fitting alternatives, and yet your app may qualify as a true OOP app nevertheless. Often, inheritance is overused and better refactored as composition/aggregation. Remember that inheritance breaks encapsulation.

Originally posted by beetle
Javascript inheritance is both clunky and rarely useful. I've written lots and lots of OOP javascript, and I agree with mordred: composition and aggregation are much more useful facilities of OO when talking javascript. I'm not saying JS inheritence is never right, I'm just saying it very rarely is. The types of tasks we use Javascript for just don't need it.

I think one of the biggest benefits that OO JS offers has been mentioned, but not highlighted yet by this thread: multiple instances.

Going to answer to both those at once, because I feel they are both related, and that some of my message here is getting lost: the only feature difference between object oriented and object based systems is type/object inheritance. Granted, I've not said it straight out, but the comparisons should have made the fact clear. JavaScript objects are not fixed, as they are in most compiled languages. This leads to that you can dynamically change objects and prototypes, which means that instead of using subclasses you manipulate your objects and instances. This makes a flat inheritance tree much more suited for JavaScript than a deep inheritance tree. But this flattening the inheritance tree also leads to that most of your objects are actually first level in the inheritance tree, and in those cases there is no benefit to using object orientation instead of an object based system. Aggregation and composition can be made as easily from an object based system, true encapsulation is provided by closures, and the code is cleaner.

Which lead me to the second part of what Peter said - in JavaScript inheritance very rarely is the right thing.


I said in my post above, "for every task the tools best equiped for the purpose". By which I did not mean that you should avoid using object orientation in all cases. What I meant was that you should not use object orientation if inheritance is not a required feature. Nor did I mean that you should continue to pollute the global namespace by coding procedurally. I meant that you should use the programming method best suited for the purpose, and that in most cases, object based, functional style programming is better than any other style you might happen to use. Concentrate on what task you want your JavaScript to perform, not what structures you use in performing said task.

Oh. just before I forget it: Multiple instances can as easily be achieved by object based systems as object oriented. Unless you use a closure to that effect, they will not inherit, but again, inheritance is not a very useful feature in JavaScript.



Well, let's return to another thing - why I think my cookies library is a really good example of why object orientation does not make things more readable or understandable. Here's the pretty printed, nice names version of my cookies library:
var cookie={
Get:function(name){
var
re=new RegExp(name+'=([^;]*);?','gi'),
result=re.exec(document.cookie)||[];
return unescape(result.length>1?
result[1]:
null);
},
Set:function(name, value, expirationTime, path, domain, secure){
var
time=new Date;
if(e)
time.setTime(time.getTime()+(expirationTime*8.64e7));
document.cookie=name+
'='+
escape(value)+
'; '+
(!expirationTime?
'':
'; expires='+time.toUTCString())+
(!path?
'':
'; path='+path)+
(!domain?
'':
'; domain='+domain)+
(!secure?
'':
'; secure');
},
Del:function(name, path, domain){
var
value=this.Get(name);
document.cookie=name+
'='+
(!path?
'':
'; path='+path)+
(!domain?
'':
'; domain='+domain)+
'; expires=Thu, 01-Jan-70 00:00:01 GMT';
return value;
},
Sup:function(){
this.Set('c',true);
return this.Del('c');
}
};and here's an object oriented cookies handling library (they aren't doing exactly the same thing, so there's some difference there, but I still think they pretty much show what I mean)
function Cookies(){
var
oCookies={},
aRawCookies=document.cookie.split(/;/g),
i=aRawCookies.length,
aTemp;

function Cookie(name, value){
this.name=name;
this.toString=function(){
return value;
};
}

while(i-->0){
aTemp=aRawCookies[i].split(/=/g);
oCookies[aTemp[0]]=new Cookie(aTemp[0],aTemp[1]);
}

this.munch=function(name){
return (typeof oCookies[name]!='undefined')?
oCookies[name]:
false;
}

this.bake=function(name, value, expirationTime, path, domain, secure){
oCookies[name]=new Cookie(name, value);
document.cookie=name+
'='+
escape(value)+
'; '+
(!expirationTime?
'':
'; expires='+time.toUTCString())+
(!path?
'':
'; path='+path)+
(!domain?
'':
'; domain='+domain)+
(!secure?
'':
'; secure');
}
this.trash=function(name, path, domain){
var
value=this.munch(name);
document.cookie=name+
'='+
(!path?
'':
'; path='+path)+
(!domain?
'':
'; domain='+domain)+
'; expires=Thu, 01-Jan-70 00:00:01 GMT';
if(typeof oCookies[name]!='undefined')
delete oCookies[name];
return value;
}

this.bake('cookiesSupport', true);
this.support=this.trash('cookiesSupport');
}

var cookiejar=new Cookies;

beetle
02-16-2004, 01:00 AM
I think there's a semantic confusion here, liorean. I think I'm assuming correctly when I say just about everyone equates "object orientation" and "object based" when talking about javascript.

liorean
02-16-2004, 01:25 AM
Yes, there certainly is. And because of that I'm going to ask this:
- What makes one of the code snippets object oriented and the other object based?
- What is the technical difference between cookiejar and cookie, if you ignore how their members work?

beetle
02-16-2004, 01:34 AM
Because one is a constructor and the other is not -- it's a static object.

liorean
02-16-2004, 02:03 AM
Well, not quite. Cookies and Cookie are the constructors. I was talking about cookiejar (from the second code sample) and cookie (from the first code sample).

(Besides, I didn't intend that question for you to reply on, I know you understand what I mean here. I was trying to get one of those that argued against what I said before to give a view on it.)

RadarBob
04-11-2004, 01:48 AM
I just re-read the majority of this thread; as I was googling for "javascript inheritance" in preparation for a project. Which leads me to a situation which looks like a good candidate for using inheritance..

How about when manipulating data from a normalized database? One might aruge that composition could/will fill the bill, but inheritance seems to be a natural fit for the data. Much of the data seems to have a "is a" relationship vis-a-vis a "has a" relationship - although there may be some of that too. My "spidey sense" is telling me that inheritance will be a good way to hold the data, structured, in javascript - nicely mirroring the (intended) data design.

We have "components" of different "types". All component has common attributes, like name, price, an ID. But the different types carry very different sets of attrubutes. And there are many different types and likely to be more in the future. Additionally certain types have interdependancies, or perhaps a different set of rules for the same dependancy. Make sense? Kinda fuzzy maybe, being so generic here.

So waddya think?

Code Wizard
04-11-2004, 03:40 PM
Not really much to do with the general subject,but I remember asking some time ago how to create a static property or metod,such as the Math object has,also the Date object has a few static methods if I'm not mistaken...
Well I got the asnwer:

function Object(param1,param2)
{
//Code here...
}

Object.staticProp=5;
Object.staticMethod=function(){...} ;



&Stuff...

Garadon
04-11-2004, 07:19 PM
composition is not the same as inheritance.

composits can see each public interfaces either one way or both ways.

in inheritance the child can see its parent's public,protected interface.

RadarBob
04-12-2004, 02:22 PM
Not really much to do with the general subject,but I remember asking some time ago how to create a static property or metod,such as the Math object has,also the Date object has a few static methods if I'm not mistaken...
Well I got the asnwer:

function Object(param1,param2)
{
//Code here...
}

Object.staticProp=5;
Object.staticMethod=function(){...} ;
C.W.
Are you saying that because "staticProp" is a property of the Object object that it is unchangeable? Couldn't I do this?


var ObjectofMyDesire = new Object
ObjectofMyDesire.staticProp = 20;

Code Wizard
04-12-2004, 11:12 PM
Sorry haven't coded anything in quite a while(my recent post was just a reminiscence) but I'll give it a shot...altough I could be wrong...



var ObjectofMyDesire = new Object
ObjectofMyDesire.staticProp = 20;

The code u wrote would create a new empty object,for which u could then assign properties(and methods).
If we could write it's constructor function,it would probably look like this(also,I believe the (empty)Object object is only implemented in MS JScript):


function Object()
{
return this;
}

The fact is that this piece of code would assign a prop to an instance,not to the constructor:


ObjectofMyDesire.staticProp = 20;

To assign a static property(or method),you have to assign the value(or function) to the object constructor.
Hope I made that clear enough :cool:

RadarBob
04-13-2004, 02:08 PM
Sorry, I'm confusing myself. I was thinking 'constant' not static. But static in the java sense means there is only one instance, and it's available to all objects of that class. JS does not have classes, so as I understand the Javascript object model, JS does not have a static-like feature.

OK loriean is going to chime in here any minute now!

Code Wizard
04-13-2004, 06:14 PM
Well,static in teh JScript sense,means that the particular property(or method) is accesible only from the object's constructor.
Just think at the Math object's methods and props - u never create a Math object on your own,you just use it's (static) methods and properties.
Also,looking at the Date object - you can make new instances of it,but I suggest you to look at it's parse() method...
There is nu such thing as "unchangeable" in JScript,as it doesn't have features that allow you to protect your data from being changed.
There IS a techinique that's called a Closure(I suggest you google it up) that seems to allow some data hiding,but still,you won't find any information on this in any recent book.

RadarBob
04-13-2004, 06:25 PM
There is nu such thing as "unchangeable" in JScript,as it doesn't have features that allow you to protect your data from being changed.
Not yet! I've read documentation that says CONST is a reserved word in JS - but not implemented.

Choopernickel
04-13-2004, 07:12 PM
CONST would be a very welcome addition.

I don't know if the following is a "closure," but it keeps properties from changing, provided you don't mind the extra coding:

function Constructor () {
self = this; // fixes privatization bug
this.publicVar = 'some public value, hence changeable';
var hiddenVar = 'some constant value';
this.getHiddenVar = function () {
return hiddenVar;
}
}
instance = new Constructor();
public = instance.publicVar; // works fine
// hidden = instance.hiddenVar; // throws error
hidden = instance.getHiddenVar(); // works fine
instance.hiddenVar = 'different value'; // creates a new non-inheritable property of this object
alert(instance.hiddenVar == instance.getHiddenVar()); // alerts 'false'

Using an accessor method prevents access to the actual value stored in the initialized object.

Code Wizard
04-13-2004, 11:14 PM
This is quite strange,as I am SURE I've read an example of using const in "JavaScript Unleashed",where it said that u can use const,altough no checking is done to stop you from modifing the value...

RadarBob
04-13-2004, 11:25 PM
This is quite strange,as I am SURE I've read an example of using const in "JavaScript Unleashed",where it said that u can use const,altough no checking is done to stop you from modifing the value...
Javascript Unleashed - 3rd edition says "Javascript does not support constants..." The CONST reserved word is not mentioned.

Pure Javascript - 2nd edition says "the word const is reserved for future use. There is no definition at this time."

beetle
04-14-2004, 01:33 AM
Ah yes, closures - I use them quite a bit in JS

Caffeine
04-14-2004, 09:36 AM
Very interesting thread!
I have started OOP:ing just recently so this thread has been very useful so far :thumbsup:


One question though which I could not find an answer to: [I've searched the forums and googled for it]

Where can I read more about this bug, I have no idea of why it's needed or what it does ?


...

function Constructor () {
self = this; // fixes privatization bug
...

Code Wizard
04-14-2004, 12:16 PM
RadarBob

I have the book,and I quite clearly says what I've posted above,also providing an example with the const keyword in use.
I think this mistake appears because it's a version translated in romanian...


Caffeine

I have just the link 4 u:
http://www.crockford.com/javascript/private.html
;)

It isn't a bug...it's just that JScript has a rather simplistic OO model,I don't really believe that it was supposed to support such a thing as private data...
Closures are just a workaround for this,that's why you don't see them in any book related to JavaScript...or am I wrong...?

Choopernickel
04-14-2004, 03:14 PM
So... is what I posted indeed a closure?

beetle
04-15-2004, 01:28 AM
I agree with Code Wizard - this really doesn't seem like a bug - just a shortcoming of JS's OO. A "bug" implies that it's supposed to do something and doesn't - when I don't believe it was supposed to.

A closure is basically when you have access to function-level scope after that function has already returned. A prime exaple is if you use a function to apply event handlers.



function myObject( id )
{
var self = this; // function-level scope reference to object
this.obj = document.getElementById( id );

this.clickHandler = function()
{
alert( "I've been clicked!" );
}

this.obj.onclick = function() { self.clickHandler() } // this is the closure
}

Unless I'm misunderstanding the concept, this is a good example. The clickHandler() method can be called at anytime - certainly long after the myObject constructor has returned - however, through the scope chain we've established, it still has access to the function-level scoped variable self

Code Wizard
04-15-2004, 11:53 AM
As a side note,can anyone give a good explanation of `self ' ,does it only reffer to the current object,like the this keyword...I thought it was used like the window object (instead of writing window.prop ,you could write self.prop - so does this apply to any object type aswell...?)

beetle
04-15-2004, 03:06 PM
Ah, well, it's simpler than that.

In the global context, self exists as a reference to the current window. But, it's pretty useless, IMO. Why? We already have window for that.

So, not being worried about writing over self (or having trouble accessing the global one), it's the perfect variable name to use for a reference to the current object. However, one could just as easily choose another name for this variable.

So, in the context of my example, it has no automatic value - it's just a variable, which I explicity declare


var self = this;

Got that?

glenngv
04-15-2004, 03:30 PM
Maybe this is a non-confusing name

var me = this;

:)

Code Wizard
04-15-2004, 08:36 PM
Ah yes,indeed,now I see the light :thumbsup:
Hence I never used this techinique(if i could called it that),of overwriting default objects;
self is there for flexibility,u can use it instead of window...
But aren't some core objects write protected,can I just overwrite them all...?
Can I just set window.opener(on a new window) to null ,or set the document object to null...is there any advantage in doing so ?
Wow! Not that's a lot of questions ! :p
Hope there's any1 to answer them...
Anywayz,I must agree this thread is progressing quite nicely :)

Roy Sinclair
04-15-2004, 09:19 PM
I would avoid the overwriting of core objects for a couple reasons:

They may be unprotected in the browser you use but who can say about all browsers?

Some other script may count on that value not being changed.

However what Beetle did wasn't the same (assuming that he did that within a function which is a reasonable assumption), he defined a new locally scoped variable which only happens to have the same name as a global object which only makes that global object unavailable within that scope and wouldn't be a problem for this particular object.

Code Wizard
04-15-2004, 09:43 PM
Yes,I know he was just declaring a local variable,by using var.
If we have a variable defined inside a function with the same name as a global one,like this:


var value
function F()
{
var value
...
}

Then we could acces the global variable from within the function like this:


window['value']=...
or
window.value=...
or
self['value']=...
or
self.value=...

But the real interesting bit,is how could we access the self object(equivalent of the window object) inside the function were we already have defined a local variale called self...
Now,if there would be no equivalent for self,we could not access this object from within the function.
The same would be if we had a variable called window declared inside a function... ;)


In the global context, self exists as a reference to the current window. But, it's pretty useless, IMO. Why? We already have window for that.

Now,do you see why we have both window and self?
It's called flexibility.
Now,I'm not saying this example is it's the only reason why we have window and self,but it's certainly a thing to keep in mind.

Code Wizard
04-16-2004, 12:36 AM
Now,back to the original topic.
It's quite amazing how JS treats most things as objects,in fact,each data type that can't be defined by the language's standard data types,is treated as an object.
I would even go to say that everything in JS is an object...(well,umm almost).
When you see a "string",there you have an object,an array is a data type defined by an object(in fact,in old JS implementations you had to define your own array object,it wasn't implemented by default);
Everything that has visual impact on the page you handle with objects,even the primitive data types can be viewed as objects - as they have their own wrapper objects.
Even when writing:


var x=2564;

you can think of objects ,as x is now a property of the window object.
This leads to the conclusion that JS is not Object-Oriented,it is object based(as stated in a previous post).
That's just coz objects have a much greater role than in other languages.
What were trying to do is emulate some concepts that can be found in OO languages(Polymorphism,Encapsulation,Data hiding,Inheritance ...)
So,for how many of these can we say that we have an alternative in JS?

(When you come to think about it,seeing the list of words reserved for future use,it's all clear that we'll be having classes,public,private members and so on...heh,so in any future JS implementation,all this thing about closures would be of no use)

liorean
04-17-2004, 02:19 AM
I gather you haven't been sniffing around the ECMA specifications lately? Because there are interesting documents at <http://www.mozilla.org/js/language/>, both the Netscape JavaScript 2.0 specification, the Netscape ECMA-262 4ed proposal (of which both were last updated 2003-06-30), and a link to the ECMA-262 4ed draft, last updated 2003-03-24.

They are implementing a classical inheritance system. They are also adding typed variables, and a few new native types (Never, Void (what was formerly Undefined), Integer, Type, char; and the machine types sbyte, byte, short, ushort, int, uint, long, ulong, float). It's still backward compatible (though ECMAScript 3 was not forward compatible, so a JS1.5 parser will choke on some rather simple JS2.0)

Some reserved words are no longer reserved. Some new are added. None of the type names are reserved words, for instance, but they are constants in the global scope.



They are in other words making ECMAScript 4 more machine close, and closer to C++, further from functional languages. However, behind the scenes, things that are clearly a movement to the functional style are taking place. Primitives are no longer distinguished from compound data types - you can now create members of primitives, which you couldn't in ECMAScript 3. This means a movement towards object orientation, but also a movement towards the functional system of placing more weight in expressions and values, instead of variables and types, an effect standing in contrast to the imperative style. Closures play the same role as they did in ECMAScript 3, but they have taken a less important place as classes have come to take the place constructor functions took before - not that constructor functions are banished, they are just made redundant by the addition of classes to which you may assign custom constructors. They have sadly chosen to build a classical system for inheritance instead of extending the prototyped system of ECMAScript 3, which I would have preferred. Anyway, this means some things - you can now have virtual and final variables, which you couldn't in ECMAScript 3. It also means that classes have a broken (from an ECMAScript 3 POV) delegation system. They inherit at creation moment, and the member lookup is not exactly the same, since in ECMAScript 3 you were guaranteed that there were only a single member with a given name, which you are not in the namespaced and more complicated ECMAScript 4 system.




Well, enough about a future which is still far away. (Though Mozilla may very well be getting somewhere with JavaScript 2.0 this year, considering how close to complete Epimetheus is.)

Well, let's have a look at object orientation for a while.

Inheritance: ECMAScript 3 is pretty clear on this. Inheritance can be done both by aggregation and by dynamic lookup. Closures and a bit of trickery allows us to create public, private and even protected members. And we can create privileged members as well (public members with access to private members). For more information on this, I would recommend not only Douglas Crockford (http://www.crockford.com/javascript/private.html) which you all should know by now, but also the a bit more technically correct Jeff Yates (http://www.pbwizard.com/Articles/class_inheritance.htm). There. That also covers Encapsulation, as that is just what private, public and protected members mean. How about Polymorphism, then? Well, ECMAScript performs implicit type coercion when required, and you may force it usinbg explicit coercion as well. We may not create operators and that means that operator overloading outside what is built in to the native types is prevented, and we may not declare more than one function with the same name. However, we aren't entirely left behind here. We have a dynamic, weakly typed language. That means that though we can't force the type of arguments sent to a function, we may detect them and act thereupon inside the function - the process of code forking. Abstraction is one of the points where functional languages are going strong. JavaScript supports higher order functions and lambda abstractions for control abstraction, and is object based and has an expression based variable handling, which in itself provides some measure of data abstraction. Objects - well, you said it. Everything is an object. It has most criteria for object orientation - and those it doesn't have are those that essentially divides weakly typed languages from strongly typed languages, and dynamic langauges from static - criterions that are very biased towards compiled, imperative languages, because that's their way of data handling.

Code Wizard
04-17-2004, 03:59 PM
Alright...now....my first question in this thread was about uses of OOP in JS.
The biggest problem I think,is that browsers lack a decent way of storing objects,so they can be used the next time the browser loads the page(this is also reffered to as persistence).
Of course there are cookies,but this involves a lot(too much,in fact) of string manipulation ,and reconstructing objects,making the whole proces too awkward.
Also IE has a few other ways of it's own for persisting data,that can be used to a greater extent,but they are far from perfect...
So,objects concerning JavaScript can be put to use only in the context of the current (browser) session...


I gather you haven't been sniffing around the ECMA specifications lately?
True,I'm actually speaking now more from a theoretical point of view,than from what I've learnt in practice.

Hobbes
09-07-2010, 09:55 AM
Hi I am Hobbes, totally new to posting in these forums. I create web based mmorpg's. I mainly use php and javascript as my main scripting languages. I just wanted to post a little info + a question.

Regarding: var self = this;

The only use of this if seen is in this situation:


function foo(){

this.methodA = function(){

var self = this;

setTimeout( function(){ self.methodB(); }, 100);

};

this.methodB = function(){

alert('fire');

};

}

var someObject = new foo();

This is the only way that I have found to perform object methods invoked by a timer ( using this.method(); fails since the this keyword is out of scope within the timer ).

Now I have a question regarding such a use: does "var self = this;" create a duplicate object, doubling the memory usage? If so will "self = null;" at the end of the timer:


setTimeout( function(){ self.methodB(); self = null; }, 100);

fix this hypothetical issue?

Dormilich
09-07-2010, 11:28 AM
this is just a Closure, so there is no "double" object.

PS.

Function.prototype.bind = function (obj) {
var fn = this;
return function () {
return fn.apply(obj, arguments);
}
};
and

// though unnecessary in this example case
// setTimeout(this.methodB, 100) would suffice
setTimeout(this.methodB.bind(this), 100);

Hobbes
09-07-2010, 06:20 PM
Interesting indeed :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum