Given:
var x = function () {
};
x.prototype = { abc: 25 };
Can someone explain to me what this means. Could this be done all inside a function without the .prototype?
var x = function () {
// something here ?
};
Given:
var x = function () {
};
x.prototype = { abc: 25 };
Can someone explain to me what this means. Could this be done all inside a function without the .prototype?
var x = function () {
// something here ?
};
Prototypes are how the class model works in JavaScript - you've created a class x
that has a property abc
which defaults to 25
:
var obj = new x();
alert(obj.abc); // 25
The function x
is the class constructor, it is called when a new instance of that class is created and can initialize it. And that means of course that you can just set the abc
property there:
var x = function()
{
this.abc = 25;
};
var obj = new x();
alert(obj.abc); // 25
This is supposedly the less efficient approach however:
ECMAScript Harmony has a nicer syntax for defining classes and prototypes, however this one isn't implemented in any browser yet:
class x {
constructor() {
...
}
public abc = 25;
}
This is equivalent to your code defining the prototype, merely grouping related operations a little better.