Javascript OO syntax

There seem to be many different ways to do OO in JavaScript.

I like:

function ClassA(){}; ClassA.prototype={ someFunc:function(a,b,c){}, otherFunc:function(){} } var c=new ClassA(); 

and never used functions other than what it provides (even though they are experienced OOer). I suspect this is old-fashioned, because every time I see new options with sparkles, and this makes me wonder if I choose the best approach. For example, you can do magic in the constructor method to create private variables and access methods, which I thought (until relatively recently) was impossible. How about a subclass? I would not know how to do this, but he already has some kind of general picture.

How do you do it and why?

+6
javascript oop
Sep 16 '10 at 0:30
source share
7 answers
 function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; return { publicMethod: function() { alert(iAmAPrivateVariable); }, publicVariable: bar() } } //usage var thing = foo() 

This is called a functional appoach since you are actually using locks for encapsulation (which is the only way to do this in javascript).

In general, you should not do OO in javascript, it is not such a big language for it for many reasons. Think of a diagram with short-angle brackets and half-columns, and you will start writing a language like professionals. In this case, once OO is better suited. In such cases the above is usually the best choice.

EDIT: mix inheritance

 function parent() { return { parentVariable: 2 }; } function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; me = parent(); me.publicMethod = function() { alert(iAmAPrivateVariable); }; me.publicVariable = bar(); return me; } 

This makes things a little more complicated, but achieves the desired end result, but at the same time uses a functional approach to OO concepts (in this case, using decorator functions instead of real inheritance). What I like about the whole approach is that we continue to view objects as they are intended to be in that language - a bag of property to which you can attach material as you wish.

EDIT2:

Just wanted to give credit, this approach is a very easy simplification to what doug crockford offers in Javascript: The Good Parts. If you want to take your js skills to the next level, I would really like to start there. I don’t think I learned so much from such a small book.

One more note: this is wildly different from what you will see most of the time on most tasks that you will ever work on, and it is often very difficult to explain a) what is happening, and b) why it is a good idea for colleagues.

+6
Sep 16 '10 at 0:40
source share
— -

Simple JavaScript Inheritance

Because John Resig said so.

+5
Sep 16 2018-10-06T00: 00Z
source share

JavaScript's “subclassification” usually refers to prototype-based inheritance, which basically follows this pattern:

 function Superclass() { } Superclass.prototype.someFunc = function() { }; function Subclass() { } Subclass.prototype = new Superclass(); Subclass.prototype.anotherFunc = function() { }; var obj = new Subclass(); 

This creates a prototype chain from obj -> Subclass.prototype -> Superclass.prototype -> Object.prototype .

Nearly every OOP library for JavaScript relies on this technique, providing features that abstract away most of the magic prototype.

+2
Sep 16 '10 at 0:44
source share

I think joose is a pretty cool way to do OOP in javascript
http://code.google.com/p/joose-js/

+1
Sep 16 2018-10-09T00:
source share

Objects in JavaScript are different from almost all other high-profile languages. Instead of being based on classes (for example, in Java, C ++, PHP, etc.), They are based on prototypes. Thus, the main paradigm of object-oriented programming should be significantly changed. People who cannot or don't want to rethink this and insist on using class-based thinking should build class-based logic in JavaScript or use code from someone else who has already created it.

+1
Sep 16 2018-10-09T00:
source share

I like to do something like

 // namespace "My" var My = new function { // private methods /** * Create a unique empty function. * @return {Function} function(){} */ function createFn () {return function(){}} /** A reusable empty function. */ function emptyFn () {} /** * Clone an object * @param {Object} obj Object to clone * @return {Object} Cloned object */ function clone (obj) { emptyFn.prototype=obj; return new emptyFn() } // public methods /** * Merge two objects * @param {Object} dst Destination object * @param {Object} src Source object * @param {Object} [options] Optional settings * @return {Object} Destination object */ this.merge = function (dst, src, options) { if (!options) options={}; for (var p in src) if (src.hasOwnProperty(p)) { var isDef=dst.hasOwnProperty(p); if ((options.noPrivate && p.charAt(0)=='_') || (options.soft && isDef) || (options.update && !isDef)) continue; dst[p]=src[p]; } return dst; } /** * Extend a constructor with a subtype * @param {Function} superCtor Constructor of supertype * @param {Function} subCtor Constructor of subtype * @param {Object} [options] Optional settings * @return {Function} Constructor of subtype */ this.extend = function (superCtor, subCtor, options) { if (!subCtor) subCtor=createFn(); if (!options) options={}; if (!options.noStatic) this.merge(subCtor, superCtor, options); var oldProto=subCtor.prototype; subCtor.prototype=clone(superCtor.prototype); this.merge(subCtor.prototype, oldProto); if (!options.noCtor) subCtor.prototype.constructor=subCtor; return subCtor; } } 

And then something like ...

 // namespace "My.CoolApp" My.CoolApp = new function(){ // My.CoolApp.ClassA this.ClassA = new function(){ // ClassA private static var count=0; // ClassA constructor function ClassA (arg1) { count++; this.someParam=arg1; } // ClassA public static My.merge(ClassA, { create: function (arg1) { return new ClassA(arg1); } } // ClassA public My.merge(ClassA.prototype, { doStuff : function (arg1) { alert('Doing stuff with ' + arg1); }, doOtherStuff : function (arg1) { alert('Doing other stuff with ' + arg1); } } return ClassA; } // My.CoolApp.ClassB this.ClassB = new function(){ My.extend(My.CoolApp.ClassA, ClassB); // ClassB constructor function ClassB () { ClassA.apply(this, arguments); } return ClassB; } } 

... the clone function is the key to inheritance. In short:

  • Clone an object by creating a prototype of the throwaway function and calling the function with "new".
  • Clone the prototype of the parent constructor and set it as the prototype of the child class.
0
Sep 16 '10 at 1:20
source share

OOP in Javascript for Canvas

See how useful OOP in js might be in a different situation ... This allows you to draw squares and circles as objects so you can go back and iterate or process them as you see fit.

 function Shape(x,y,color){ this.x = x this.y = y this.color = color } function Square(height,width,color){ Shape.call(this, event.x, event.y, color) this.height = height this.width = width this.x -= canvas.offsetLeft + (this.height/2) this.y -= canvas.offsetTop + (this.width/2) } Square.prototype = new Shape(); Square.prototype.draw = function(color){ ctx.fillStyle = color ctx.fillRect(this.x,this.y,this.height,this.width) } function Circle(color, width){ Shape.call(this) this.x = event.x -60 this.y = event.y -60 this.width = width } Circle.prototype = new Shape(); Circle.prototype.draw = function(color){ ctx.beginPath() ctx.arc(this.x,this.y,this.width,0,2*Math.PI, false); ctx.fillStyle = color ctx.fill() } 
0
Jul 16 '15 at 1:39
source share



All Articles