js 笔记
这两天在看精通javascript一书,其中有很多写得很好的代码。现作个记录,留着以后用:
var Class = { //这是prototype 里的书法,用来生成一个空的构造函数。 create: function() { return function() { this.init.apply(this, arguments); } } } Object.extend = function(destination, source) { //扩民对象 for (var property in source) { destination[property] = source[property]; } return destination; } var person = Class.create(); Object.extend(person.prototype, { //给person添加公共方法 init: function(name) { this.name = name; }, getName: function() { return this.name; }, setName: function(newName) { this.name = newName; }, setAge: function(newage) { this.age = newage; } }); var user = Class.create(); //创建user user.prototype = Object.extend(new person(), { //扩展person的一个实例,并返回给user.prototype init: function(name, age) { this.name = name; this.age = age; }, getName: function() { return 'my name is : ' + this.name; }, getAge: function() { return this.age; } });
//这样一来,user的实例将会有上面所有的方法了。 var test = new user(); test.init('zjh', 28); test.setName('sky'); alert(test.getName()); alert(test.getAge()); test.setAge(18); alert(test.getAge());