-1

Consider the following:

Are the following code piece equivalient ?

var foo = Class.create();
foo.prototype = {
    initialize : function() {};
    sayHello : function() {};
}

and

    var foo = Class.create();
    foo.prototype = {
        initialize : function() {};
    } 
   foo.prototype.sayHello : function() {};

Secondly, which one to prefer other the other ? when and why ?

1
  • Maybe the following answer can help you understand what prototype does and what a constructor function or initializer does.stackoverflow.com/a/16063711/1641941 Commented Mar 5, 2014 at 0:01

1 Answer 1

1

They're both wrong, they should be

var foo = new Object();
foo.prototype = {
  initialize : function() {},
  sayHello : function() {}
}

and

var foo = new Object();
foo.prototype = {
    initialize : function() {}
} 
foo.prototype.sayHello = function() {};

and yes they're the same

I prefer the first way for initialize because is more clear

Sign up to request clarification or add additional context in comments.

4 Comments

@JavaDeveloper class is not a javascript object, maybe it's from any framework
var Person = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } };
@JavaDeveloper "In early versions of Prototype, the framework came with basic support for class creation", it's a framework, Class is not a built-in object of javascript
@JavaDeveloper i don't know prototype framework so i guess Class.create() is fine with it, i prefer code in pure javascript or with jquery personally; with jquery for example you can add functions directly to the jQuery object prototype

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.