Prototype
JavaScriptのPrototype ≒ JavaのSuperClass
★Prototype Chain
function Object1(param){
this.number = param;
}
function Object2(param){
this.string = param;
}
Object2.prototype = new Object1(10);
var myObj = new Object2("xxx");
alert(myObj.string); //xxx
alert(myObj.number); //10
alert(myObj.toString); //function(Objectに属する)
alert(myObj.dummy); //undefined
重複の場合
function User(){
this.name = 'BBB';
}
User.prototype.name = 'CCC';
var user = new User();
user.name = 'AAA';
console.log(user.name); //AAA
delete user.name;
console.log(user.name); //CCC
delete User.prototype.name;
console.log(user.name); //undefined
typeof(String.prototype); // object
typeof(User.prototype); // object
typeof(user.prototype); // undefined インスタンスの場合
prototypeによりAPIを拡張
if(!Array.prototype.pushs) {
//Array.prototype = { pushs: function(){...} }; // × 再定義できない
Array.prototype.pushs = function() { // 〇
var pos = this.length;
for(var i=0; i<arguments.length; i++) {
this[pos++] = arguments[i];
}
return this.length;
};
}
var test = ['a','b','c'];
test.pushs('d','e');
var str;
for(var key in test){
str += ' ' + key;
}
console.log(str); //0 1 2 3 4 pushs
var str;
var value;
for(var key in test){
if(test.hasOwnProperty(key)) {
str += ' ' + key;
value += ' ' + test[key];
}
}
console.log(str); //0 1 2 3 4
console.log(value); //a b c d e
★Prototype基本
function Cat(name, color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "xxx";
Cat.prototype.eat = function(){...};
var cat1 = new Cat("A","white");
var cat2 = new Cat("B","black");
alert(cat1.constructor == Cat); //true
alert(cat1 instanceof Cat); //true
alert(cat1.eat == cat2.eat); //true
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
alert("name" in cat1); // true
alert("type" in cat1); // true