Yes, using literals for prototype
is correct. For example Mozilla explicitly uses a literal in the prototype's documentation:
var Customer = function(name) {
this.name = name;
}
var Person = { // this is a literal
canTalk : true,
greet : function() { /* ... */ }
}
Customer.prototype = Person;
Some explanation: Value of prototype
is an object. It doesn't matter how the object was created - using simply {}
is fine. It is often initialized using something like MyClass1.prototype = new MyClass2()
, but new
just creates a new object. It also sets the prototype
property and executes the constructor (MyClass2
) but on the new object, it doesn't affect MyClass1
in any way (see explanation here).
Using a nested literal doesn't make a difference. In the question, the prototype is set to { literal : { ... } }
. What actually happens when you call inst.literal.init()
is:
- The runtime looks at
inst
and checks whether the object has a value assigned for property literal
.
inst
dos not have such property, therefore the runtime continues with its prototype
property
inst.prototype
references the literal object to which it was initialized. This object has assigned a value for property literal
.
inst.literal
therefore evaluates to the nested literal inst.prototype.literal
- The literal object does have a value for property
init
- The
init()
function is called
This is one of the principles of JavaScript (ECMA Script) so there should be no compatibility issues.