且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

js深入研究之Person类案例

更新时间:2022-09-05 23:35:52

<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深入研究之Person类案例

js的类很有意思,没想到js还有类这种概念。jQuery或者一些插件中,经常会用到这些属性,研究透了,才能够看得懂,甚至自己去写一个自己的类。


本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5048734.html,如需转载请自行联系原作者