3、构造器调用模式
var People = function(string){
this.name = string; // 构造器调用模式中,this 被绑定到了新对象上。即,所有new出来的People对象都有一个name属性
}
People.prototype.get_name = function(){
return this.name;
}
var person = new People("cherry"); // 构造器模式调用
document.write(person.name); // cherry
document.write(person.get_name()); // cherry
4、Apply调用模式
func.apply(this,agrs); //apply调用模式接受两个参数;this代表func方法的应用对象,即this对象可以使用func这个函数;args是参数数组。
var arr1 = [1,2,3];
var arr2 = [3,4,5];
Array.prototype.push.apply(arr1,arr2); // arr1.push(3,4,5); 就是这个意思。
console.log(arr1); // 1,2,3,3,4,5
var max = Math.max.apply(null,arr2); // Math.max(3,4,5); 就是这个意思。
console.log(max);
函数参数
当函数被调用时,会得到一个“免费”奉送的参数,那就是arguments数组。这使得编写一个无需指定参数个数的函数成为可能。
//构建一个将n个值相加的函数
var sum = function(){
var i, sum = 0; //这个sum为函数作用域
for(i=0; i<arguments.length; i+=1){
sum += arguments[i];
}
return sum;
};
console.log(sum(1,3,4,5)); //13
//给类型补充方法,不要覆盖原有方法
Object.prototype.method = function(name,func){
if(!this.prototype[name]){ //this 代表 Object 对象
this.prototype[name] = func;
return this;
}
};
String.method("trim",function(){
return this.replace(/^\s+|$\s+/g, "");
});
var str = " he ll ";
console.log(str.length); //8
str = str.trim();
console.log(str.length); //4
String.method("split",function(){
console.log("heoo split");
});
var arr = str.split(" "); //split()还是原来的方法
console.log(arr); //[ "he", "", "ll"]