3

In the following article, Douglas Crockford creates a function to more closely simulate prototypical inheritance in JavaScript (http://javascript.crockford.com/prototypal.html). I understand the concept. However, once you create a new object using the function below, how do you then add methods and properties to that object other than using dot/subscript notation. Either of which, in my opinion, would produce ugly code.

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

newObject = Object.create(oldObject);

Do I then need to use the following notation?

newObject.method1 = function(){}
newObject.cnt = 1;
...

Does anyone else find this as an ugly way to add properties and methods to an object?

I understand I can technically pass in a function, for which I want to set the prototype of, with all the methods and variables.

I'm more or less trying to understand how Crockford intended for that function to be used.

MAK
  • 26,140
  • 11
  • 55
  • 86
Steve
  • 53,375
  • 33
  • 96
  • 141

1 Answers1

3
var prototypeForNewObject = {
  method: function (x) { ... },
  prototypeProperty: 42
};

var newObject = Object.create(prototypeForNewObject);

// Adding an instance property
newObject.cnt = 1;

And instead of using Crock's version, I would use the full EcmaScript 5 signature that includes an optional propertiesObj argument. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create

You might find the examples at that link informative.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • Good to know about. That's more or less how I would expect the function signature to look like. Just trying to understand how Crock intented the function to be used. – Steve Jun 12 '11 at 16:51
  • 2
    @Steve, your best bet to understand his intent might be to send him an email at the address at the top of the page to which you linked. My avatar is a stuffed (and rather fat) t-rex eating a jar of vegemite. T-rex forelimbs are not good at opening jars, so it has to eat the jar whole. – Mike Samuel Jun 12 '11 at 17:05
  • 2
    That is ridiculous...Everyone knows that t-rex's do not eat vegemite. Maybe Crock should come on StackOverflow instead. – Steve Jun 12 '11 at 19:18