js方法调用的四种模式
1、方法调用模式
1 function Persion() { 2 ????var name1 = "itcast", 3 ????age1 = 19, 4 ????show1 = function() { 5 ????????console.log(this.name); 6 ????}; 7 ?8 ????return { 9 ????????age : age1,10 ????????name : name1,11 ????????show : show112 ????};13 }14 15 var p = new Persion();16 p.show(); ?//在show方法中的this指向了p对象。
2、 函数调用模式
1 function add( a, b) {2 ????this.result = a + b;3 }4 5 add( 3, 9 ); //此方法执行的时候,this指向了window6 7 console.log(result); ??
3、构造器调用模式
1 function Persion(){ 2 ????this.name = "123"; 3 ????this.age = 19; 4 ????this.show = function(){ 5 ????????console.log(this.name); 6 ????}; 7 } 8 ?9 var p = new Persion();10 p.show();// ?在show方法中方法this,指向了p对象实例。
4、call 和 apply调用模式
1 function add(a,b){2 ????this.result = a + b;s ??????????3 }4 5 var p ?= {}; ???????//定义一个空对象。6 add.call(p,3,4); ???//在这个方法调用的时候,this指向了p7 console.log(p.result);8 9 //apply和call是一样的用法,只不过apply第二个参数用数组进行传递。
变量提升:函数执行之前,会先将函数中所有的变量,挪到最前面去声明。
函数名提升: script中脚本,在执行之前,会先把脚本中的所有的函数先进行编译解析,然后执行普通的js代码。
第164天:js方法调用的四种模式
原文地址:https://www.cnblogs.com/le220/p/8400219.html