<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<title>Prototype</title>
</head>
<body>
<div class="container"></div>
<script type="text/javascript">
function Animal(type){ // create a class
this.type = type;
}
Animal.prototype = { // add attribute or methods to class by using .prototype
age : 0, // add attribute
setAge : function(age) { // add method
this.age = age;
console.log("Age is set to: " + this.age);
},
introduce : function(){
console.log('This is ' + this.name);
}
}
function Cat(name){ // create a class
this.name = name;
};
Cat.prototype = new Animal('Cat'); // add Animal's attributes and methods to Cat class
var kate = new Cat('kate'); // create an instacne of Cat
function Dog(name){
this.name = name;
};
Dog.prototype = new Animal('Dog');
Dog.prototype.introduce = function(){ // overwrite Dog class' "introduce" function which cloned from Animal
console.log('wow ' + this.name);
};
var shiba = new Dog("shiba"); // create instacnes of Cat
var hachi = new Dog("hachi");
hachi.introduce = function(){ // overwrite object hachi's "introduce" function
console.log('chi qiang');
}
console.log(shiba.type); // Dog
kate.setAge(6); // Age is set to: 6
kate.introduce(); // This is kate
shiba.introduce(); // wow shiba
hachi.introduce(); // chi qiang
</script>
</body>
</html>
javascript prototype [note]
最新推荐文章于 2024-08-17 21:49:37 发布