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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.