Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add sample for constructor

  • Loading branch information...
commit c59896c67fa2a282ef3e6c9e1dc02fc57355af66 1 parent d5b7fac
Kazuya NUMATA authored

Showing 2 changed files with 50 additions and 0 deletions. Show diff stats Hide diff stats

  1. +20 0 7/src/circle.js
  2. +30 0 7/test/circle_test.js
20 7/src/circle.js
... ... @@ -0,0 +1,20 @@
  1 +function Circle(radius) {
  2 + if (!(this instanceof Circle)) {
  3 + throw new Error();
  4 + }
  5 + this.radius = radius;
  6 +}
  7 +
  8 +(function (p) {
  9 + p.diameter = function () {
  10 + return this.radius * 2;
  11 + };
  12 +
  13 + p.circumference = function () {
  14 + return this.diameter() * Math.PI;
  15 + };
  16 +
  17 + p.area = function () {
  18 + return this.radius * this.radius * Math.PI;
  19 + };
  20 +}(Circle.prototype));
30 7/test/circle_test.js
... ... @@ -0,0 +1,30 @@
  1 +TestCase("CircleTest", {
  2 + "test inspect objects" : function () {
  3 + var circ = new Circle(6);
  4 + var circ2 = { radius: 6 };
  5 +
  6 + assertTrue(circ instanceof Object);
  7 + assertTrue(circ instanceof Circle);
  8 + assertTrue(circ2 instanceof Object);
  9 + assertEquals(Circle, circ.constructor);
  10 + assertEquals(Object, circ2.constructor);
  11 + },
  12 + "test should create another object of same kind": function () {
  13 + var circle = new Circle(6);
  14 + var circle2 = new circle.constructor(9);
  15 + assertEquals(circle.constructor, circle2.constructor);
  16 + assertTrue(circle2 instanceof Circle);
  17 + },
  18 + "test should inherit properties from Circle.prototype" : function () {
  19 + var circle = new Circle(6);
  20 + assertEquals(12, circle.diameter());
  21 + },
  22 + "test constructor is Object when prototype is overridden": function () {
  23 + function Circle() {}
  24 + Circle.prototype = {};
  25 + assertEquals(Object, new Circle().constructor);
  26 + },
  27 + "test calling prototype without 'new' returns undefined": function () {
  28 + assertException(function() { Circle(6);}, "Error")
  29 + }
  30 +});

0 comments on commit c59896c

Please sign in to comment.
Something went wrong with that request. Please try again.