JavaScript 函数有 4 种调用方式, 每种方式的不同在于 this 的指向不一样。 在Javascript中 this 是保留关键字,一般而言,this指向函数执行时的当前对象。
通常情况下我们可以用函数名称加圆括号()调用函数
function fun1(x, y,) {
console.log(x+y);
return x + y
}
fun1(5, 10); // 15
当函数没有被自身的对象调用时 this 的值就会变成全局(window) 对象。
var color = 'red';
function fun1() {
console.log(this);
return this.color
}
console.log(fun1()); // 'red'
定义object对象的方法
var person = {
user: "yoyo",
age: 50,
address: function () {
// do something...
console.log(this);
return this.user
}
};
console.log(person.address()) // "yoyo"
实例中 this 的值为 person 对象
如果函数调用前使用了 new 关键字, 则是调用了构造函数。 这看起来就像创建了新的函数,但实际上 JavaScript 函数是重新创建的对象
// 构造函数:
function myFunction(arg1, arg2) {
this.user= arg1;
this.age = arg2;
}
// new
var x = new myFunction("yoyo", 20);
console.log(x.user) // yoyo
console.log(x.age) // 20
JavaScript 函数是对象, 函数有它的属性和方法。每个函数都包含两个属性:length和prototype prototype 下面有两个方法 apply(),call(),这两个方法都是函数非继承而来的方法, 是每一个函数都具有的方法。 这两个方法的用途都是在特定的作用域中调用函数(看this指向的作用域是谁),也就是说调用特定的对象下面调用函数
function func(x, y) {
return x + y;
}
var res = func.call(this, 10, 20);
console.log(res); // 30
var res= func.apply(this, [10,20]);
console.log(res); // 30
call()方法第一个同样是作用域,其余的参数是逐个传递给函数的,而不是传递一个数组过去。 apply()方法有两个参数,第一个是要执行这个方法的作用域,也就是传递一个对象过去,第二个参数是一个数组. 如果函数不需要传参,那么后面的参数是可以省略的。
var user = 'hello';
var person = {
user: 'yoyo',
age: 20
}
function myName(){
return this.user;
}
console.log(myName()); //hello this是window
console.log(myName.call(window)); //hello this是window
console.log(myName.call(this)); //hello this是window
console.log(myName.call(person)); //yoyo this是person
console.log(myName.call(null)); //hello this是window
使用这apply()和call()这两个方法最大的好处是对象不需要与函数有耦合关系,也就是上面说的对象中可能不存在这个方法,但只要存在这个对象就行。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有