JavaScript 新技能

1. 立即执行函数 匿名函数

(function(){
	console.log("123");
})();

2.闭包函数

function cwm1()
{
		var N=0; //N是cwm1的局部变量

		 function cwm2()  //cwm2是cwm1的内部函数,是闭包
		 {
		 	N+=1; //内部函数使用了外部函数的变量N	
		 	console.log(N);

		 }

		 return cwm2;
}

var result=cwm1();

result();
result();
result();

3.使用闭包定义私有变量

function ProductCwm()
{
	var name;

	this.setName=function(value){
		name=value;
	}

	this.getName=function(){
		return name;
	}
}

var p= new ProductCwm();

p.setName('cwm');

console.log(p.name);

console.log(p.getName());

4. prototype 继承属性和方法

function Rectangle(x,y)
{
	this._length=x;
	this._breadth=y;
}

Rectangle.prototype.getDimensions=function()
{
	return {
		length:this._length,
		breadth:this._breadth
	}	
}

var x=new Rectangle(3,4);

var y=new Rectangle(4,3);

console.log(x.getDimensions());
console.log(y.getDimensions());

5.模块化

var module=(function(){
	
	var N=5;

	function print(x){

		console.log("this result is:"+x);

	}

	function add(a)
	{
		var x=a+N;
		print(x);
	}
	return {
		description:'this is description',
		add:add

	}


})();

console.log(module.description);

console.log(module.add(10));

6.柯里化

var add = function(x){
	return function(y){
		return x+y;
	}
}

var add1=add(1);
console.log(add1(1));

console.log(add(1)(2));

7.apply,call与bind方法

var user={
    name:"CWM",
    whatIsYourName:function(){
        console.log(this.name);
    }
}
user.whatIsYourName();
var user1={
    name:"Test Name"
}

user.whatIsYourName.call(user1);

<!-- apply方法与call方法类似。两者唯一的不同点在于,apply方法使用数组指定参数,而call方法每个参数单独需要指定: -->

//var user={
// greet:'Kello',
// greetUser:function(userName)
// {

//    console.log(this.greet+"--"+userName);
// }
//}

//user.greetUser("cwm");

//var greet1={
// greet:'cwm'
//}

//user.greetUser.call(greet1,'world')

//user.greetUser.apply(greet1,['wordle'])

<!-- 使用bind方法,可以为函数绑定this值,然后作为一个新的函数返回: -->

var user={
name:'cwm',
schollname:function(scholl)
{
  console.log(this.name+''+scholl);
}
}

var geruser=user.schollname.bind({name:'IloveYour'});

var getuser=user.schollname.bind({name:'YSSA'});

//geruser('beijingdaxue');
//getuser('nanjingdashu');

9. Memoization 记忆

<!-- /Memoization用于优化比较耗时的计算,通过将计算结果缓存到内存中,这样对于同样的输入值,下次只需要中内存中读取结果。 -->
function MemoizationFunction(func) { var cache={}; return function(){ var key=arguments[0]; if(cache[key]) { return cache[key]; }else { var val=func.apply(this,arguments); cache[key]=val; return val; } } } var fibonacci = MemoizationFunction(function(n) { return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2); }); //console.log(fibonacci(100)); // 输出354224848179262000000 //console.log(fibonacci(100)); // 输出354224848179262000000

  

 

---------------未完待续-------------

posted @ 2017-07-20 10:57  继续生活  阅读(213)  评论(0)    收藏  举报