I am trying to understand an example from Douglas Crockford’s “Javascript: The Good Parts”, Chapter 1 “Good Parts”, regarding inheritance. Specifically the superior function. In the book it is as follows:
Object.method('superior', function(name) {
var that = this, method = that[name];
return function() {
// Why can’t this just be `return method`?
return method.apply(that, arguments);
};
});
As mentioned in the code comment above I don’t understand why we need to use apply when simply returning the function itself seems to work find in my experimentation.
Supplementary Info
The above uses a method function defined as
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
This is a bit of a convoluted way of doing things indeed. One possible advantage is that the resulting function will automatically bind to the initial this context (i.e you will subsequently be able to call it without having to reference the instance).
I guess the following implementation would reveal the intention more clearly:
Object.method("superior", function(name) {
var that = this, method = that[name];
return method.bind(that);
});
(This possible advantages is not directly apparent from the coolcat example on the next page as the get_name method does not make use of a this context.)
Related
I would like to override a Javascript built-in function with a new version that calls the original (similarly to overriding a method on a class with a version that calls super in many languages). How can I do this?
For example...
window.alert = function(str) {
//do something additional
if(console) console.log(str);
//super.alert(str) // How do I do this bit?
}
Store a reference to the original function in a variable:
(function() {
var _alert = window.alert; // <-- Reference
window.alert = function(str) {
// do something additional
if(console) console.log(str);
//return _alert.apply(this, arguments); // <-- The universal method
_alert(str); // Suits for this case
};
})();
The universal way is <original_func_reference>.apply(this, arguments) - To preserve context and pass all arguments. Usually, the return value of the original method should also be returned.
However, it's known that alert is a void function, takes only one argument, and does not use the this object. So, _alert(str) is sufficient in this case.
Note: IE <= 8 throws an error if you try to overwrite alert, so make sure that you're using window.alert = ... instead of alert = ....
There is no "super". Anyway, create a closure to "keep" around the original function-object.
Note the "self invoking function" that returns a new function-object (that is assigned to the window.alert property). The new function-object returned creates a closure around the variable original which evaluates to the original value of window.alert that was passed in to the "self invoking function".
window.alert = (function (original) {
return function (str) {
//do something additional
if(console) {
console.log(str)
}
original(str)
}
})(window.alert)
However, I believe some browsers may prevent alert and other built-ins from being modified...
Happy coding.
I'm assuming your question is how do you overwrite a built-in and still be able to call it. First off as a disclaimer, you should never overwrite built ins unless you have a good reason for doing it since it will make it impossible to debug/test.
This is how you would do it:
window._alert = window.alert;
window.alert = function(str) {
if(console) console.log(str);
window._alert(str);
}
How to do simple classical inheritance in Javascript:
SuperClass.call(this) // inherit from SuperClass (multiple inheritance yes)
How to override functions:
this.myFunction = this.myFunction.override(
function(){
this.superFunction(); // call the overridden function
}
);
The override function is created like this:
Function.prototype.override = function(func)
{
var superFunction = this;
return function()
{
this.superFunction = superFunction;
return func.apply(this,arguments);
};
};
Works with multiple arguments.
Fails when trying to override undefined or nonfunctions.
Makes "superFunction" a "reserved" word :-)
JavaScript does not use a classical inheritance model. There is a nice article here which describes a way to write your classes so that a similar syntax can be used, but it's not natively supported.
By using proxy object you can do this.
window.alert = new Proxy(window.alert , {
apply: function(target,that,args){
console && console.log(args.join('\n'));
target.apply(that,args)
}})
I'll admit I'm flailing around, cobbling code together from different authors in an attempt to figure out javascript prototypes.
I'm new to the prototype concept, and would like to have some instance variables in my class that can be modified using a method.
Here's what I'm trying, in essence. This was cribbed and modified from the web:
var MyGlobe = function () {
var self = this;
self.variable1 = null;
return self;
}
MyGlobe.prototype = function () {
var setup = function () {
this.variable1 = 33;
};
return {
setup:setup
};
}();
...the point of all that is so I can call the setup method on an instance of MyGlobe and set variable1 properly:
var aGlobe = new MyGlobe();
aGlobe.setup();
//aGlobe.variable1 is 33 now
This actually seems to work, but I'm not sure why the original author did things this way? For instance, what's the point of the self.variable1 bit at the beginning?
Is it preferable to typing out:
MyGlobe.prototype.variable1;
MyGlobe.prototype.variable2;
//....
I also thought you'd do something like self=this if you thought your class would be used in a callback function for example, but that doesn't appear to be the case here? (Happy to be shown wrong.)
I'm not sure what the best practices are here and would like to know more.
This actually seems to work, but I'm not sure why the original author did things this way? For instance, what's the point of the self.variable1 bit at the beginning?
None (for using self), the "declaration of instance properties" (even if only initialising them to null) can help engines to use more memory-efficient internal structures - though it's not really necessary.
I also thought you'd do something like self=this if you thought your class would be used in a callback function for example, but that doesn't appear to be the case here?
Exactly. This small snippet really should be rewritten to
var MyGlobe = function () {
this.variable1 = null;
}
MyGlobe.prototype.setup = function() {
this.variable1 = 33;
};
Is it better to declare the instance variables in the constructor function (self.variable1) as opposed to adding them to the prototype (MyGlobe.prototype.variable1)?
That's simple. On the prototype it's no instance property any more. And please distinguish between variables (like self - which are local-scoped to the function) and properties (like prototype, setup or variable1 - which are "public" on the object).
In attempting to keep with the DRY principle, I decided to revise a function's prototype in an effort to reduce the number of function.call() calls.
Following is a snippet of what I currently have and further clarification as to what I am attempting to do.
com.domain.$ = function(s){
if(!this){return new com.domain.$(s);}
this.selector = s;
this.elements = document.querySelectorAll(s);
}
com.domain.$.prototype = (function(){
function exe(f){
var e = this.elements,
el = e.length;
for(var i=0; i<el; i++){
f(e[i]);
}
}
function addClass(c){exe.call(this,function(el){el.classList.add(c);});}
function removeClass(c){exe.call(this,function(el){el.classList.remove(c);});}
function toggleClass(c){exe.call(this,function(el){el.classList.toggle(c);});}
return {
addClass:addClass,
removeClass:removeClass,
toggleClass:toggleClass
}
}());
I realize this looks very much like I am attempting to mimic the functionality of jQuery. While intentional, this is not meant to act as a replacement but rather a better personal understanding of JavaScript.
That said, what I would like to do is remove the need to invoke exe() via exe.call(this[, fnc]); in order for the context of this to be what I want. I believe I can do this through function binding (.bind()), though perhaps not the way I would like to. I understand it is possible to instead do something like:
com.domain.$.prototype.exe = function(){}
and call it like:
function addClass(c){this.exe(function(){});}
In doing so, however, I lose the private visibility of exe() provided by the closure in my original code. I would like to keep that in tact, if possible.
My question, then, is whether or not it is possible to bind exe() within my original code in such a way that I can reduce the redundant use of exe.call(this, possess the correct context for this within exe(), and maintain the private visibility within the closure?
If this seems a poor implementation of what I am trying to accomplish, I am more than happy to consider other options.
Thank you in advance.
No, you can't, since at the moment you define exe(), the instance you want to call exe() on does not exist yet.
In fact, if you are going to make several calls to com.domain.$, you will use exe() with different instances and therefore it does not make sense to bind exe() to a specific instance.
If you wanted to do that, you'd have to define all these methods inside the constructor and you would loose all the advantages of prototypes:
(function() {
function exe(f){
// ...
}
com.domain.$ = function(s){
// ...
var exe_ = exe.bind(this);
this.addClass = function(c) {
exe_(function(el){el.classList.add(c);});
};
// ...
};
}());
I would suggest, if you don't want to use .call, to just modify exe() so that it accepts an array of elements as argument and pass this.elements to it from the prototype functions. I don't see why exe() needs to use this at all. It's merely a helper which passes each element of an array to a given function and by making it more general, it is easier to reuse.
For example:
var com.domain.$ = (function(o) {
function exe(arr, f){
var el = e.length;
for(var i=0; i<el; i++){
f(arr[i]);
}
}
var $ = function(s){
// ...
}
$.prototype.addClass = function(c){
exe(this.elements, function(el){
el.classList.add(c);
});
};
// ...
return $;
}());
I'm hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so that I can just do
var vehicle = new Vehicle(el);
var model = vehicle->getModel();
These functions would read the HTML and get and manage the elements on the page. I'm current doing a setup like...
var model = function () {
return {
getName: function () {
},
getVehicleCount: function () {
},
incrementCount: function (id) {
console.log(x);
}
}
}();
I'm still learning classes in Javascript... I'd like to be able to pass the class a node for the element all of the methods will use, but I'm not sure I'm doing this right...
There is no such thing as a class in JavaScript, instead everything in JavaScript is an object.
To create a new object you define a function that uses the this keyword in it (a “constructor function”), and then call it with the new operator:
function Foo (id) { // By convention, constructor functions start with a capital letter
this.id = id;
}
var foo1 = new Foo(1);
var foo2 = new Foo(2);
However, these objects have no methods. To add methods, you need to define a prototype object on their constructor function:
Foo.prototype = {
getId: function () {
return this.id;
}
}
This new getId function will be usable by all Foo objects. However, as was stated, there are no classes in JavaScript and as such there are other constructs you will use in order to produce different results.
I highly recommend the videos by Douglas Crockford in which he explains much of the javascript OO nature. The talks can be found here:
http://developer.yahoo.com/yui/theater/
Douglas Crockford — The JavaScript Programming Language
Douglas Crockford — Advanced JavaScript
Those will give you a basic understanding of the structure of javascript and should help the transition from classical to functional programming.
Although there are no classes in JavaScript, you can create constructor functions. A constructor function works by binding methods to an objects prototype. There are several ways to do this, each with advantages and disadvantages. I personally prefer the most straigthforward way, which works by appending methods to "this":
var Constructor = function() {
//object properties can be declared directly
this.property = "value";
//to add a method simply use dot notation to assign an anonymous function to an object
//property
this.method = function () {
//some code
}
//you can even add private functions here. This function will only be visible to this object methods
function private() {
//some code
}
//use return this at the end to allow chaining like in var object = new Constructor().method();
return this;
}
There is nothing like classes in JavaScript. JavaScripts inheritance works with prototypes. You can take a look at base2, which mimics class-like behaviour in JavaScript.
I'm trying to get the principles of doing jQuery-style function chaining straight in my head. By this I mean:
var e = f1('test').f2().f3();
I have gotten one example to work, while another doesn't. I'll post those below. I always want to learn the first principle fundamentals of how something works so that I can build on top of it. Up to now, I've only had a cursory and loose understanding of how chaining works and I'm running into bugs that I can't troubleshoot intelligently.
What I know:
Functions have to return themselves, aka "return this;"
Chainable functions must reside in a parent function, aka in jQuery, .css() is a sub method of jQuery(), hence jQuery().css();
The parent function should either return itself or a new instance of itself.
This example worked:
var one = function(num){
this.oldnum = num;
this.add = function(){
this.oldnum++;
return this;
}
if(this instanceof one){
return this.one;
}else{
return new one(num);
}
}
var test = one(1).add().add();
But this one doesn't:
var gmap = function(){
this.add = function(){
alert('add');
return this;
}
if(this instanceof gmap) {
return this.gmap;
} else{
return new gmap();
}
}
var test = gmap.add();
In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:
var gmap = function() {
this.add = function() {
alert('add');
return this;
}
this.del = function() {
alert('delete');
return this;
}
if (this instanceof gmap) {
return this.gmap;
} else {
return new gmap();
}
}
var test = new gmap();
test.add().del();
By assigning the new gmap();to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".
In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.
Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be.
Sadly, the direct answer has to be 'no'. Even if you can override the existing methods (which you probably can in many UAs, but I suspect cannot in IE), you'd still be stuck with nasty renames:
HTMLElement.prototype.setAttribute = function(attr) {
HTMLElement.prototype.setAttribute(attr) //uh-oh;
}
The best you could probably get away with is using a different name:
HTMLElement.prototype.setAttr = function(attr) {
HTMLElement.prototype.setAttribute(attr);
return this;
}
To "rewrite" a function, but still be able to use the original version, you must first assign the original function to a different variable. Assume an example object:
function MyObject() { };
MyObject.prototype.func1 = function(a, b) { };
To rewrite func1 for chainability, do this:
MyObject.prototype.std_func1 = MyObject.prototype.func1;
MyObject.prototype.func1 = function(a, b) {
this.std_func1(a, b);
return this;
};
Here's a working example. You just need to employ this technique on all of the standard objects that you feel need chainability.
By the time you do all of this work, you might realize that there are better ways to accomplish what you're trying to do, like using a library that already has chainability built in. *cough* jQuery *cough*
First, let me state that i am explaining this in my own words.
Method chaining is pretty much calling a method of the object being returned by another function/method. for example (using jquery):
$('#demo');
this jquery function selects and returns a jquery object the DOM element with the id demo. if the element was a text node(element), we could chain on a method of the object that was returned. for example:
$('#demo').text('Some Text');
So, as long as a function/method returns an object, you can chain a method of the returned object to the original statement.
As for why the latter don't work, pay attention to where and when the keyword this is used. It is most likely a context issue. When you are calling this, make sure that this is referring to that function object itself, not the window object/global scope.
Hope that helps.
Just call the method as var test = gmap().add();
as gmap is a function not a variable