facebook twitter hatena line email

Javascript/javascriptオブジェクト指向

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

javascriptオブジェクト指向サンプル

<script type="text/javascript">
<!--
var test = function(name) {
 this.name = name;
 this.width = new Array();
}
test.prototype = {
 call : function() {
  alert(this.name + "さん。");
 },
 hallo : function() {
  alert(this.name + "さん。おはよう。");
 }
}
var t = new test("satou");
//-->
</script>
<a href="" onClick="t.call();t.hallo();return false;">do</a>
参考
http://builder.japan.zdnet.com/sp/javascript-kickstart-2007/story/0,3800083428,20369263,00.htm?ref=rss

オブジェクト継承

function Animal(){
}
Animal.prototype.name = function(){
  return 'animal';
};
Animal.prototype.foot = function(){
  return 'foot undefined';
};
var animal = new Animal();
console.log(animal.name()); // animal

function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

Cat.prototype.name = function(){
  return 'cat';
};
Cat.prototype.foot = function(){
  return 4;
};
Cat.prototype.all = function(){
  return this.name() + this.foot(); // 内部メソッド
};
var cat = new Cat();
console.log(cat.name()); // cat
console.log(cat.foot()); // 4
console.log(cat.all()); //cat4

オブジェクト継承でextendを使う

function Animal(){
}
Animal.prototype.name = function(){
  return 'animal';
};
Animal.prototype.foot = function(){
  return 'foot undefined';
};
var animal = new Animal();
console.log(animal.name()); // animal

/**
 * extend function
 * @param {Object} s superclass
 * @param {Function} c constructor
 */
function extend(s, c)
{
    function f(){};
    f.prototype = s.prototype;
    c.prototype = new f();
    c.prototype.__super__ = s.prototype;
    c.prototype.__super__.constructor = s;
    c.prototype.constructor = c;
    return c;
};

function Cat(){
}
Cat = extend(Animal, function()
{
    // this.__super__.constructor();
});

Cat.prototype.name = function()
{
    // console.log(this.__super__.name());
    return 'cat';
}
var cat = new Cat();
console.log(cat.name());

注意:extendが他と被る恐れあり

参考 http://plusb.jp/blog/?p=102