Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this JavaScript augmented method work?

Tags:

javascript

Similar to this question, I am following Douglas Crockford's JavaScript, The Good Parts. In chapter 4, he talks about augmenting types, which I find very confusing. He writes this sample code:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

Number.method('integer', function (  ) {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

He then tests the new integer method:

document.writeln((-10 / 3).integer());  // -3

I don't understand the syntax of this.prototype[name] (in particular, the brackets) or Math[this < 0 ? 'ceiling' : 'floor'](this) (again, the brackets and also where Math came from). More importantly, can someone explain how the code in general works, and why the test code works?

like image 727
joshreesjones Avatar asked Feb 14 '26 23:02

joshreesjones


1 Answers

By extending Function.prototype you add a method available to every function. Remember that functions in JavaScript are objects, and as such they can have properties and methods eg. call or apply.

The method function method lets you add a method to the prototype of any given function. Number is a function; the constructor of numbers, which has a prototype. Functions that you add to the prototype are available for all instances of the object, in this case a number.

Math is a built-in object in JavaScript, by using bracket notation you can dynamically access the property of an object. Remember that object keys are just strings, even if you don't write them as string, they can still be accessed with bracket notation with a string, for example:

var obj = {
  key: 'hello'
};

var k = 'key';

obj[k]; //=> 'hello'

In the case of Math it's simply deciding if it should use ceil (not "ceiling") or floor based on a condition, you could write like this:

if (this < 0) {
  Math.ceil(this);
} else {
  Math.floor(this);
}
like image 152
elclanrs Avatar answered Feb 16 '26 11:02

elclanrs