object[name] = function () {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof old === 'function') {
return old.apply(this, arguments);
}
}
}
addMethod(people, "find", function () {
return this.values;
});
addMethod(people, "find", function (firstName) {
var ret = [];
for (var i = 0; i < this.values.length; i++) {
if (this.values[i].indexOf(firstName) === 0) {
ret.push(this.values[i]);
}
}
return ret;
});
addMethod(people, "find", function (firstName, lastName) {
var ret = [];
for (var i = 0; i < this.values.length; i++) {
if (this.values[i] === (firstName + ' ' + lastName)) {
ret.push(this.values[i]);
}
}
return ret;
});
console.log(people.find());
console.log(people.find("Sam"));
console.log(people.find("Dean Edwards"));
JS跨浏览器绑定事件函数
常规实现方法
//跨浏览器添加事件
function addHandler(target, eventType, handler) {
//检测浏览器类型,并且重写addHandler方法
if (target.addEventListener) {
addHandler = function (target, eventType, handler) {
target.addEventListener(eventType, handler, false);
}
} else { //IE
addHandler = function (target, eventType, handler) {
target.attachEvent("on" + eventType, handler);
}
}
//调用新的函数
addHandler(target, eventType, handler);
}
//跨浏览器移除事件
function removeHandler(target, eventType, handler) {
//检测浏览器类型,并且重写addHandler方法
if (target.addEventListener) {
removeHandler = function (target, eventType, handler) {
target.removeEventListener(eventType, handler, false);
}
} else { //IE
removeHandler = function (target, eventType, handler) {
target.detachEvent("on", eventType, handler);
}
}
target.detachEvent("on" + eventType, handler);
}
优化方法
//绑定事件
var addHandler = document.body.addEventListener ?
function (target, eventType, handler) {//DOM2
target.addEventListener(eventType, handler, false);
} :
function (target, eventType, handler) {//IE
target.attachEvent("on" + eventType, handler);
};
//移除事件
var removeHandler = document.body.removeEventListener ?
function (target, eventType, handler) {
target.removeEventListener(eventType, handler, false);
} :
function (target, eventType, handler) {
target.detachEvent("on" + eventType, handler);
};
JS单体模式
var shoppingCar = (function () {
//这个是由购物车构造器所创建的实例
var instance;
//购物车的构造器函数
function Trolley() {
this.date = new Date().getDate();//实例属性,当前日期
}
//原型属性,一个返回当前日期的方法
Trolley.prototype.getDate = function () {
return this.date;
};
//暴露出去的公共API
return function () {
//如果实例不存在,那么就调用Trolley构造器实例化一个
if (!instance) {
instance = new Trolley();
}
//将实例返回外部
return instance;
}
}());
var a = new shoppingCar();
var b = new shoppingCar();
console.log(a === b);//true
使用prototype属性定义的对象方法
var dom = function () {};
dom.Show = function () {
alert("Show Message");
};