JavaScript Tutorial 6: custom object

Javascript tutorial (学习笔记) 系列基本上翻译自 “A re-introduction to JavaScript (JS Tutorial)” 加上自己学习过程中的心得体会.  这一篇是第六篇(接Javascript Tutorial (学习笔记) 6):

Custom objects (Javascript中的类的用法)

Note: For a more detailed discussion of object-oriented programming in JavaScript, see Introduction to Object Oriented JavaScript.

In classic Object Oriented Programming, objects are collections of data and methods that operate on that data. JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. (This is sometimes confusing for programmers accustomed to languages with a class statement.) Instead, JavaScript uses functions as classes. Let’s consider a person object with first and last name fields. There are two ways in which the name might be displayed: as “first last” or as “last, first”. Using the functions and objects that we’ve discussed previously, here’s one way of doing it:

function makePerson(first, last) {
    return {
        first: first,
        last: last
    }
}
function personFullName(person) {
    return person.first + ' ' + person.last;
}
function personFullNameReversed(person) {
    return person.last + ', ' + person.first;
}
> s = makePerson("Simon", "Willison");
> personFullName(s)
Simon Willison
> personFullNameReversed(s)
Willison, Simon

This works, but it’s pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an object. Since functions are objects, this is easy:

function makePerson(first, last) {
    return {
        first: first,
        last: last,
        fullName: function() {
            return this.first + ' ' + this.last;
        },
        fullNameReversed: function() {
            return this.last + ', ' + this.first;
        }
    }
}
> s = makePerson("Simon", "Willison")
> s.fullName()
Simon Willison
> s.fullNameReversed()
Willison, Simon

There’s something here we haven’t seen before: the ‘<a title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator" href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/this" target="_blank">this</a>‘ keyword. Used inside a function, ‘this‘ refers to the current object. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an object, that object becomes ‘this‘. If dot notation wasn’t used for the call, ‘this‘ refers to the global object. This is a frequent cause of mistakes. For example:

> s = makePerson("Simon", "Willison")
> var fullName = s.fullName;
> fullName()
undefined undefined

When we call fullName(), ‘this‘ is bound to the global object. Since there are no global variables called first or last we get undefined for each one.

We can take advantage of the ‘this‘ keyword to improve our makePerson function:

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = function() {
        return this.first + ' ' + this.last;
    }
    this.fullNameReversed = function() {
        return this.last + ', ' + this.first;
    }
}
var s = new Person("Simon", "Willison");

We’ve introduced another keyword: ‘<a title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operator" href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/new" target="_blank">new</a>‘. new is strongly related to ‘this‘. What it does is it creates a brand new empty object, and then calls the function specified, with ‘this‘ set to that new object. Functions that are designed to be called by ‘new‘ are called constructor functions (这里的Person就是我们的构造函数, function关键字在这里就有点类似C++/Java里面的class关键字). Common practise is to capitalise these functions as a reminder to call them with new.

Our person objects are getting better, but there are still some ugly edges to them. Every time we create a person object we are creating two brand new function objects within it — wouldn’t it be better if this code was shared?

function personFullName() {
    return this.first + ' ' + this.last;
}
function personFullNameReversed() {
    return this.last + ', ' + this.first;
}
function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = personFullName;
    this.fullNameReversed = personFullNameReversed;
}

That’s better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

function Person(first, last) {
    this.first = first;
    this.last = last;
}
Person.prototype.fullName = function() {
    return this.first + ' ' + this.last;
}
Person.prototype.fullNameReversed = function() {
    return this.last + ', ' + this.first;
}

<span style="color: #ff0000;">Person.prototype</span> is an object shared by all instances of Person. It forms part of a lookup chain (that has a special name, “prototype chain“): any time you attempt to access a property of Person that isn’t set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this object.

This is an incredibly powerful tool. JavaScript lets you modify something’s prototype at any time in your program, which means you can add extra methods to existing objects at runtime (其实看本章的标题custom object然后联系到前文的object介绍, 这些东西其实是很自然的很统一的, 因为这里Person.prototype.X其实就是在定义Person.prototype[X] = Y, 因为在javascript中什么都是object, 那么就理解成key-value pair就很自然了):

> s = new Person("Simon", "Willison");
> s.firstNameCaps();
TypeError on line 1: s.firstNameCaps is not a function
> Person.prototype.firstNameCaps = function() {
    return this.first.toUpperCase()
}
> s.firstNameCaps()
SIMON

Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let’s add a method to String that returns that string in reverse:

> var s = "Simon";
> s.reversed()
TypeError on line 1: s.reversed is not a function
> String.prototype.reversed = function() {
    var r = "";
    for (var i = this.length - 1; i >= 0; i--) {
        r += <span style="color: #ff0000;">this</span>[i];
    }
    return r;
}
> s.reversed()
nomiS

Our new method even works on string literals! (好牛逼>_<)

> "This can now be reversed".reversed()
desrever eb won nac sihT

As I mentioned before, the prototype forms part of a chain. The root of that chain is Object.prototype, whose methods include toString() — it is this method that is called when you try to represent an object as a string. This is useful for debugging our Person objects:

> var s = <span style="color: #ff0000;">new</span> Person("Simon", "Willison");
> s
[object Object]
> Person.prototype.toString = function() {
    return '<Person: ' + this.fullName() + '>';
}
> s
<Person: Simon Willison>

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the object that should be treated as ‘this‘. For example, here’s a trivial implementation of ‘new‘:

function trivialNew(constructor) {
    var o = {}; //<span style="color: #ff0000;"> Create an object</span>
    constructor.apply(o, arguments);
    return o;
}

This isn’t an exact replica of new as it doesn’t set up the prototype chain. apply() (it would be difficult to illustrate). This is not something you use very often, but it’s useful to know about.

apply() has a sister function named call, which again lets you set ‘this‘ but takes an expanded argument list as opposed to an array.

function lastNameCaps() {
    return this.last.toUpperCase();
}
var s = new Person("Simon", "Willison");
lastNameCaps.call(s);
// Is the same as:
s.lastNameCaps = lastNameCaps;
s.lastNameCaps();
Written on August 27, 2013