所谓模块化编程,就是将代码模块化,每一块代码都只进行一种操做,能够这样理解吧。javascript
模块化编程重要的一点就是,在一个模块里,全部的变量都是局部变量(对整个项目来讲,对这个模块来讲固然能够是全局变量了)java
模块化编程如何将全局变量转变为局部变量:chrome
我连那个函数这个全局变量都不想要了:编程
当即执行,直接call()
服务器
function(){ //your code }.call()
函数当即执行的优势:模块化
很差意思,chrome不支持,的解决办法:函数
前面加!
表示这是个当即执行函数。不过会对这个函数的返回值取反,不过当即执行了就没了,不关心它的返回值this
!function(){ //your code }.call()
用()
包起来。问题是若是前面有代码,好比xxx(function(){}).call()
,这就等于调用xxx了,等价于xxx().call()
。。。function(){}
只是传入的参数spa
(function(){ //your code }).call()
MVC是一种代码整理的思路.net
上面这张图能够很好的展示M和V和C之间的互动关系。
愚见:深度模块化。将全部的重复的代码都提取出来造成对象、构造函数等,在须要使用的时候,调用或者使用new
等进行操做。
button.onclick=function(){ console.log(this); }
👆上面的this
指向button
👆
button.addEventListener('click',function(){ console.log(this); })
👆上面的this
指向button
👆
$('ul').on('click','li',function(){ console.log(this); })
👆上面的this
指向li
👆
var x=X(); x.f1(option); function X(){ return object{ //①,对象object里的this都指向对象object option:null, f1(x){ this.option=x; this.f2(); //②② }, f2(){ this.option.f2.call(this); //③③③ } } } var option={ f1(){}, f2(){ console.log(this); //④④④④ } }
👆执行完头两句,最终会调用对象option的f2(){console.log(this);}
。这里的this
指向对象object👆
new
和原型链有很大关联,都是当须要建立不少不少个对象,而这些对象若是有不少相同的属性和方法,将这些相同的属性和方法提取出来,作成一个模板、原型。new
的做用就是代表用这个模板、原型新生成一个对象。
建立士兵:
createSoldier(1); function createSoldier(id){ var rookieSoldier={ ID:id, }; rookieSoldier.__proto__=createSoldier.prototype; return soldier } createSoldier.prototype={ 兵种:"火枪兵", 生命值:42, 攻击:function(){}, 防护:function(){}, 行军:function(){} }
使用new建立士兵:
👇👇👇下面createSoldier
函数里的注释内容,就是使用new
后,js自动帮你添加的(固然是看不见的)。咱们须要写的是this.ID = id
这样自定义的内容和createSoldier.prototype
公共的内容👇👇👇
new createSoldier(1); function createSoldier(id){ //var temp={}; //this = temp; //this.__proto__=createSoldier.prototype; this.ID = id; //return this; } createSoldier.prototype={ 兵种:"火枪兵", 生命值:42, 攻击:function(){}, 防护:function(){}, 行军:function(){} }
常见的new的使用:
var object = new Object(); //object.__proto__=Object.prototype var array = new Array(); //array.__proto__=Array.prototype var string = new String(); //string.__proto__=String.prototype var number = new Number(); //number.__proto__=Number.prototype
请参考:https://blog.csdn.net/a153375...
请参考:https://zhuanlan.zhihu.com/p/...
这里在讨论||
和&&
的返回值
||
或表达式中,有一个是真即返回这个真的值(第一个真值):&&
与表达式中,有一个是假即返回这个假的值(第一个假值):
注意:并非返回true
或者false
,而是返回这个真值或者假值!!!
全部的假值:NaN
0
''
undefined
false
null
0 || 12 || 'a' //返回12 var a= {} || undefined || 12 //a={}
0 && 12 && 'a' //返回0 var a= {} && undefined && 12 //a=undefined