Is either of these patterns more or less efficient than the other?
Pattern 1:
var jso = new Class({
initialize: function () {
// code
},
hiliteField: function () {
// code
}
});
Pattern 2:
var jso = new Class({
initialize: function () {开发者_开发知识库
this.hiliteField = hiliteField.bind(this);
// code
}
});
var hiliteField = function () {
// code
}
Having multiple methods that are external to the class and up the scope chain, as opposed to behind the class as 'namespaced' methods can't be better, imo.
Don't like pattern #2 for several reasons:
- manageability - having to bind a reference to each external function into the class is going to be hard to do.
- readability - having to indicate which function is being used by what class is going to be a task
- extendibility - because the functions are outside of the jso class prototype, classes that extend jso or use it as a mixin won't be able to access the external methods.
That being said, from a memory standpoint - just do a test but I would say, pattern 1 is likely to have a smaller overhead because it's defined once on the prototype and not in every instance individually.
Pattern 2 will use more memory! It's the basics of prototypal inheritance
Why? In Pattern 1 every instance of jso
will reference jsoInstanceX.hiliteField
to jso.prototype.hiliteField
. Read: hiliteField
will not be a copy, it will only exist in jso.prototype
.
In Pattern 2 you create a function wrapper each time you assign hiliteField.bind(this);
. The additional memory is not much, but it's also slower, especially with impact on Class initialization.
精彩评论