<script type="text/javascript"> /* 定义一个Person类 */ function Person(name, age) {this.name = name;this.age = age; } /* 添加两个方法getName getAge */ Person.prototype = {getName: function() {return this.name;},getAge: function() {return this.age;} }/* 实例化类 */var alice = new Person('Alice', 93); var bill = new Person('Bill', 30);/* 修改类,添加新的方法getGreeting */Person.prototype.getGreeting = function() {return 'Hi ' + this.getName() + '!'; };alert(alice.getGreeting()); // 即可生效/* 为对象添加方法,只对对象有效 */alice.displayGreeting = function() {alert(this.getGreeting()); }alice.displayGreeting(); // Hi Alice! bill.displayGreeting(); // 没有信息 </script>
js的类很有意思,没想到js还有类这种概念。jQuery或者一些插件中,经常会用到这些属性,研究透了,才能够看得懂,甚至自己去写一个自己的类。