JS面向对象编程(对象创建)
//构造函数
function Animal(name, sound, age) {
this.name = name;
this.sound = sound;
this.age = age;
}
//类属性
Animal.description = 'animal';
//类方法
Animal.descript = function() {
document.write('This is a \'' + this.description + '\' class!<br>');
}
//实例方法
Animal.prototype = {
sayName:function(str) {
document.write('My name is:' + this.name + str + '<br>');
},
shout:function() {
document.write('My sound is:' + this.sound + '!!!<br>');
},
sayInfo:function() {
document.write('Name = ' + this.name + '; Age = ' + this.age + '<br>');
}
};
//测试类
Animal.descript();
var dog = new Animal('dog', 'wang wang', 5);
var cat = new Animal('cat', 'miao miao', 3);
dog.sayName('.--wang');
cat.sayName('.--miao');
dog.shout();
cat.shout();
dog.sayInfo();
cat.sayInfo();
//输出
/**
* This is a 'animal' class!
* My name is:dog.--wang
* My name is:cat.--miao
* My sound is:wang wang!!!
* My sound is:miao miao!!!
* Name = dog; Age = 5
* Name = cat; Age = 3
**/
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sgear/archive/2008/07/27/2720194.aspx