第164天:js方法调用的四种模式

时间:2023-03-10 01:38:40
第164天:js方法调用的四种模式

js方法调用的四种模式

1、方法调用模式

 function Persion() {
var name1 = "itcast",
age1 = 19,
show1 = function() {
console.log(this.name);
}; return {
age : age1,
name : name1,
show : show1
};
} var p = new Persion();
p.show(); //在show方法中的this指向了p对象。

2、 函数调用模式

 function add( a, b) {
this.result = a + b;
} add( 3, 9 ); //此方法执行的时候,this指向了window console.log(result);

3、构造器调用模式

 function Persion(){
this.name = "123";
this.age = 19;
this.show = function(){
console.log(this.name);
};
} var p = new Persion();
p.show();// 在show方法中方法this,指向了p对象实例。

4、call 和 apply调用模式

 function add(a,b){
this.result = a + b;s
} var p = {}; //定义一个空对象。
add.call(p,3,4); //在这个方法调用的时候,this指向了p
console.log(p.result); //apply和call是一样的用法,只不过apply第二个参数用数组进行传递。

变量提升:函数执行之前,会先将函数中所有的变量,挪到最前面去声明。

函数名提升: script中脚本,在执行之前,会先把脚本中的所有的函数先进行编译解析,然后执行普通的js代码。