函数(二)----Javascript语言精粹

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"]




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值