changeset 186:241afcc93a80 javascript-exercises

Add class-exercises.js - 'class methods'.
author jf3243
date Thu, 17 Nov 2011 16:46:44 +0000
parents f7f3f25815b9
children cc20307b32db
files core-javascript/javascript-exercises/answers/class-exercises.js
diffstat 1 files changed, 60 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/core-javascript/javascript-exercises/answers/class-exercises.js	Thu Nov 17 16:07:28 2011 +0000
+++ b/core-javascript/javascript-exercises/answers/class-exercises.js	Thu Nov 17 16:46:44 2011 +0000
@@ -24,3 +24,63 @@
     assert( pt.__classname__ === 'Point' );
 
 });
+
+
+TEST('class methods', function()
+{
+    var actual;
+    var expect;
+
+    var person = {};
+    var Person = SimpleClass(person);
+
+    // Initialise a person to have a name and an age.
+    // start
+    person.__init__ = function(name, age){
+        this.name = name;
+        this.age = age;
+    };
+    // stop
+
+
+    // Test that we can create a person.
+    var someone = Person('Bob', 26);
+    assert( someone.name === 'Bob' );
+    assert( someone.age === 26 );
+
+
+    // Add a greet method to the class prototype object.
+    person.greet = function(another){
+        // start
+        var msg = "Hello " + another + ", I'm " + this.name + ".";
+        return msg;
+        // stop
+    };
+
+    // Test the greet method.
+    var tmp =  someone.greet('Alice');
+    something = "Hello Alice, I'm Bob";
+    assert( tmp = something );
+
+    // Add a goodbye method.
+    // start
+    person.goodbye = function(another){
+
+        var msg = "Goodbye, " + another + ". It was a pleasure to meet you.";
+        return msg;
+    };
+    // stop
+
+    expect = "Goodbye, Alice. It was a pleasure to meet you.";
+     actual = someone.goodbye('Alice');
+    assert( actual === expect );
+
+    // A flaw in the design.
+    var someone_else = Person('Alice', 31);
+
+    // Figure out what we get.
+    something = "Hello [object Object], I'm Bob.";
+    expect = something;
+    actual = someone.greet(someone_else);
+    assert( actual === expect );
+});