函数
1.函数的定义和调用
(1)函数的定义
<script>
//命名函数
function fn() {};
//函数表达式(匿名函数)
var fun = function() {};
//利用new Function('参数1', '参数2', '函数体');
var f = new Function('a', 'b', 'console.log(a+b)');
f(1, 2);
</script>
(2)函数的调用方式
普通函数
对象的方法
构造函数
绑定事件函数
定时器函数
立即执行函数
<script>
//普通函数
function fn() {
console.log('hhhhhhh');
}
fn(); //或者fn.call();
//对象的方法
var o = {
sayHi: function() {
console.log('hhhhhh');
}
}
o.sayHi();
//构造函数
function Star() {};
new Star();
//绑定事件函数
btn.onclick = function() {};
//定时器函数
setInterval(function() {}, 1000); //每隔一秒自动调用一次
//立即执行函数:自动调用
(function fn() {
console.log('hhhhhhh');
})();
</script>
2.this
(1)函数内this的指向
(2)改变函数内部的this指向
call()方法
<script>
var o = {
name:'andy'
}
function fn(a, b) {
console.log(this);
console.log(a+b);
}
fn.call(o, 1, 2);
</script>
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
//子构造函数
function Son(uname, age, score) {
//this指向子构造函数的实例对象
Father.call(this, uname, age);
this.score = score;
}
apply()方法
<script>
var o = {
name:'andy'
}
function fn(arr) {
console.log(this);
console.log(arr);
}
//fn.call(o, 1, 2);
fn.apply(o, ['pink']);
var arr = [1, 3, 16, 7, 10];
var max = Math.max.apply(Math, arr);//指向Math内置对象
console.log(max);
//参数必须是数组(伪数组)
</script>
bind()方法
<script>
var o = {
name:'andy'
}
function fn(a, b) {
console.log(this);
console.log(a+b);
}
var f = fn.bind(o, 1, 2);
f();
</script>
- bind()不会调用fn()函数,可以改变原函数内部this指向
- bind()最后返回一个新函数f
- 调用新函数f()
bind()方法应用
<body>
<button>点击</button>
<script>
var btn = document.querySelector('button');
btn.onclick = function() {
this.disabled = true; //1.此处this为btn
setTimeout(function() {
this.disabled = false; //3.因为2所以此处的this是btn
//假如没有绑定,此处的this将会指向windows
}.bind(this), 3000); //2.bind()将this(btn)与函数绑定
}
</script>
</body>