tddjs > Object.createを使ったオブジェクトの生成

Object.createメソッドを使ったオブジェクトの作成。 コンストラクタを使わないオブジェクトの生成

by s_hiroshi

HTML

<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css">
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>

JavaScript

if (!Object.create) {
    (function() {
        function F() {}
        Object.create = function(object) {
            F.prototype = object;
            return new F();
        };
    }());
}



function bar() {
    function _setName(name) {
        return (this.name = name);
    }

    function _getName() {
        return this.name || null;
    }
    return {
        getName: _getName,
        setName: _setName
    };
}

module('object creates without using constructor', {
    setup: function() {
        this.o1 = bar();
        this.o2 = Object.create(this.o1);
    }
});
test('test1 of object behavior', function() {
    notEqual(this.o1, this.o2);
});
test('test2 of object behavior', function() {
    this.o1.setName('o1');
    this.o2.setName('o2');
    equal('o1', this.o1.getName(), 'o1');
    equal('o2', this.o2.getName(), 'o2');
});
test('test3 of object behavior', function() {
    equal(this.o1.getName, this.o2.getName);
    strictEqual(this.o1.getName, this.o2.getName);
});