Reputation: 13927
So I'm trying to find a really clean JavaScript function prototyping pattern.
I can do this:
var Person = function () {
// person logic
}.prototype.foo = function () {
// people's foo logic
}
but I want to name my class constructor without being redundant. The following code yield unexpected .
before the word prototype
.
function Person() {
// person logic
}.prototype.foo = function () {
// people's foo logic
}
How can I define my prototype on the same line without redundantly setting Person to a variable?
Upvotes: 1
Views: 179
Reputation: 2975
"How can I define my prototype on the same line without redundantly setting Person to a variable?"
Like this (there's absolutely no redundancy here):
var Person; (Person = function() {
}).prototype.foo = function() {
};
You need a separation of the declaration of the variable and a grouping of the first assignment in order to deal with the lower precedence of the =
operator, as well as its right-to-left associativity.
But IMO, there's no benefit to this. Keep your code simple and clear.
Both your question and comment imply that you think there's some redundancy here. There is none.
Your requirement seems arbitrary, but if you really wanted this, then pass the function to a helper function that puts the pieces together.
function why(ctor, members) {
for (var m in members)
ctor.prototype[m] = members[m];
return ctor;
}
And use it like this:
var Person = why(function() {
}, {
foo: function() {
}
});
Again, no real benefit, and only added overhead, but it fulfills your requirement.
Upvotes: 2
Reputation: 7445
Is it possible? The most compact mode I know is:
var Person = function() {
this.func = function() { console.log('hello'); };
};
var p = new Person();
console.log(p instanceof Person);
console.log(typeof p.func);
p.func();
Upvotes: 0