functionPerson(name, age, job) { var o = newObject(); o.name = name; o.age = age; o.job = job; o.sayName = function () { alert(this.name); }; return o; } var friend = new Person("Nicholas", 29, "Software Engineer"); friend.sayName(); //"Nicholas"
2.7 稳妥构造函数模式
所谓稳妥对象,指的是没有公共属性,而且其方法也不引用 this 的对象。稳妥对象最适合在一些安全的环境中(这些环境中会禁止使用 this 和 new),或者在防止数据被其他应用程序(如 Mashup 程序)改动时使用。稳妥构造函数遵循与寄生构造函数类似的模式,但有两点不同:一是新创建对象的 实例方法不引用 this;二是不使用 new 操作符调用构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionPerson(name, age, job) { //创建要返回的对象 var o = newObject(); //可以在这里定义私有变量和函数 //添加方法 o.sayName = function () { alert(name); }; //返回对象 return o; }
3.继承
3.1 原型链
实现原型链有一种基本模式, 让子类构造函数的prototype属性指向父类的实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functionSuperType() { this.property = true; } SuperType.prototype.getSuperValue = function () { returnthis.property; }; functionSubType() { this.subproperty = false; } //继承了 SuperType SubType.prototype = new SuperType(); SubType.prototype.getSubValue = function () { returnthis.subproperty; }; var instance = new SubType(); alert(instance.getSuperValue()); //true
functionthrottle(func, delay) { var last; var timer; returnfunction() { var now = +newDate(); var ctx = this; var args = arguments; if (last && now - last < delay) { clearTimeout(timer); timer = setTimeout(function(){ last = now; func.apply(ctx, args); }, delay) } else { last = now; func.apply(ctx, args); } } }
6.2 函数防抖
函数防抖是指函数在n秒后触发,如果在n秒内再次被触发,那么将重新计时
1 2 3 4 5 6 7 8 9 10 11
function debounce(func, delay) { var timer; return function() { var this = ctx; var args = arguments; clearTimeout(timer); timer = setTimeout(function(){ func.apply(ctx, args); }, delay); } }