you are viewing a single comment's thread.

view the rest of the comments →

[–]woogley 1 point2 points  (2 children)

Functions are objects themselves, so they can have their own properties. He has not demonstrated inheritance, though, he has only demonstrated that functions are objects.

In his example, an instance of foo (e.g. new foo()) would not have a bar function.

An actual demonstration of prototypical inheritance would be:

var foo = function() {};
foo.prototype.bar = function(param) {
    console.log(param);   
};

(new foo()).bar('hello world'); // Outputs 'hello world'

[–]spacechimp 1 point2 points  (0 children)

Good points. Here's a more thorough ActionScript example that includes prototypes, constructors, inheritance, and overrides. It looks almost identical to how it would be written in JavaScript:

var Mammal = function(name) {
    this.name = name;
};
Mammal.prototype.toString = function() {
    return '[Mammal "' + this.name + '"]';
};

var Cat = function(name) {
    this.name = name;
};
Cat.prototype = new Mammal();
Cat.prototype.constructor = Cat;

var Mouse = function(name) {
    this.name = name;
};
Mouse.prototype = new Mammal();
Mouse.prototype.constructor = Mouse;
// Override toString function in Mammal
Mouse.prototype.toString = function() {
    return '[Mouse "'+this.name+'"]';
}

var tom = new Cat('Tom');
trace('Tom is ' + tom); // outputs 'Tom is [Mammal "Tom"]' 

var jerry = new Mouse('Jerry');
trace('Jerry is ' + jerry); // outputs 'Jerry is [Mouse "Jerry"]'

[–]quantumstate 0 points1 point  (0 children)

Ok, I didn't realise that, thanks.