2

I somewhat understand the difference between Javascript and Java when it comes to OOP. I read the bottom paragraph in the Javascript book that I have but I don't fully understand what it mean, can you further explain and provide examples to show the difference between the two languages?

"In many object-oriented programming languages, it is possible to define a class of objects and then create individual objects that are instances of that class."

Thanks!

3 Answers 3

9

What most people do is use constructor functions, like so:

function MyClass(a, b) {
    // Private instance properties
    var x = "secret";
    var y = "also secret";

    // Public instance properties
    this.a = a;
    this.b = b;

    // "Privileged" methods; can access private and public properties
    this.foo = function () {
        return x + " " + this.a;
    };
}

// "Public" methods; cannot access private properties
MyClass.prototype.bar = function () {
    return this.a + " " + this.b;
};

// Public shared properties; not recommended:
MyClass.prototype.w = "stuff";

// Static methods
MyClass.baz = function () {
    return "i am useless";
};

You would then use this constructor function like so:

var instance = new MyClass("hi", "Meen");

asssert.equal(instance.foo(), "secret hi");
assert.equal(instance.bar(), "hi Meen");
assert.equal(MyClass.baz(), "i am useless");

var also = new MyClass("hi", "Raynos");

instance.w = "more stuff";
assert.equal(also.w, "more stuff");

If you wanted to do inheritance, you would do something like:

function Inherited(a) {
    // apply parent constructor function
    MyClass.call(this, a, "Domenic");
}
Inherited.prototype = Object.create(MyClass.prototype);

var inherited = new Inherited("hello there good chap");

assert.equal(inherited.a, "hello there good chap");
assert.equal(inherited.foo(), "secret hello there good chap");
assert.equal(inherited.bar(), "hello there good chap Domenic");
Sign up to request clarification or add additional context in comments.

5 Comments

Your skimming over "private" and "privileged" without explaining that they are simply local variables in a closure and infer a run-time cost, as well as get in the way of doing prototypical OO. They are two parallel constructs and they don't work together particularly well.
Microoptimizations have never been important in my experience in doing OOP in JavaScript; being able to have one of the four tenets of OOP, viz. encapsulation, is much more important.
In that case you don't need prototypical OO. You should just have factories that mutate this. Also note "encapsulation" is met by the second definition on wikipedia.
Yes, the second definition is not what is meant by encapsulation in the context of OOP, cf. blog.ploeh.dk/2011/05/24/…
Meh, you don't need closure bound local variables for that. You can use a sensible well documented convention like ._internalName is internal, undocumented and likely to change or blow up if touched by code that uses a "class". This gives you encapsulation and prototypical OO.
4

Object oriented javascript is very simple.

You create an object.

var Klass = {
  method: function () {

  },
  constructor: function() {

  },
  ...
};

And then you create an instance of that object through prototypical inheritance

// instantiate
var o = Object.create(Klass);
// initialize
o.constructor();

This is different from classical OO because any object can be a "class" in javascript. and there is only one inheritance chain, the chain of prototypes.

Normally in classical OO languages the classes would inherit from each other and the instances would have a seperate chain of inheritance.

Also in classical OO you have two objects, the actual class object and the blueprint for the instance (i.e. static). This doesn't exist in javascript because there is only one object, the blueprint.

Disclaimer: Object.create is ES5, so you need an es5-shim for legacy platforms.

6 Comments

Oh dear, don't go pushing your favorite recently-discovered prototypes-as-classes style without at least some disclaimer... @Meen what Raynos is doing is done by very few people, and is the result of some article that's become popular within the last month; you will not see much JavaScript code in the wild like this.
@Domenic It's virtually the same thing. Klass.constructor.prototype === Klass && Constructor.prototype.constructor === Constructor. It's a matter of personal style, and I find this a lot more readable and elegant then faffing around with constructors, .prototype and new. And actually what I'm doing mirrors es.next Object exemplars and es.next classes, the ES community will move away from constructors. And besides apart from "It's not my style choice" is there anything wrong with the constructs I'm showing?
It's not virtually the same thing at all. This style separates initialization from creation via this constructor stuff, which is a substantial difference, and more importantly, this style is used by very few people on the planet. Subjective opinions about readability and elegance are trumped by whether the OP wants his code to be readable by someone who hasn't read Rauschmayer's blog post.
@Domenic meh, var KlassConstructor = Klass.constructor; var instance = new KlassConstructor(...);. They are the same. And initialization and construction has always been seperate, new just happens to do both. Personally I'd say if someone can't read the code then need to learn ES5.
Exemplars and Wirfs-Brock's "grawlixey" proposal are heavily debated; whether they will be adopted in ES.Next is entirely unclear, as is whether the community will adapt to anything like them. ES.next classes desugar to something much more like constructors than exemplars, and more importantly the emphasis on private names recognizes the importance of achieving encapsulation, one way or another; in ES5 this is only achievable through closures.
|
3

In Java you can create a class using the class keyword. A class is the blueprint for its instances (objects).

e.g.

class AClass { // AClass is a class
    AClass() { } //this is the constructor which will be used to create instances of this class
}

And then create and instance of the class:

AClass obj1 = new AClass(); // an instance of the class AClass
AClass obj2 = new AClasss(); //another instance of the class AClass

So, every object in Java is an instance of some class. And you can have many different instances of a class, but you can't have any object without class which acts as their blueprint.

And, in the class you can define member variables and methods which can either belong to the class itself, which will be shared by all of it's instances, or belong to the instance in which case every instance will have their own copy.

In Javascript I mostly create objects as follows:

var obj = { };

So, I don't need to create any class to actually create an object.

1 Comment

Haha, the simplicity of your answer makes me laugh :). +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.