vue事件中this指向window
<button v-on:click="clickBtn(this)" value="222">click me</button>
...
clickBtn (arg){
alert(arg); // 弹出 [object Window]
}
fn.call(obj, arg1, arg2);
表示:调用 fn 函数,将 arg1 和 arg2 传入函数,并将函数内的 this 指向 obj。
function add(a,b) {
alert(a+b);
}
function sub(a,b) {
alert(a-b);
}
add.call(sub,3,1); // 调用add函数,将3和1传入,如果函数中有this,将其指向sub函数。
// 结果 alert(4)
bind 函数的兼容处理
if (!Function.prototype.bind) {
Function.prototype.bind = function(obj) {
var _self = this
,args = arguments;
return function() {
_self.apply(obj, Array.prototype.slice.call(args, 1));
}
}
}
bind和call的区别
- bind返回函数,call执行函数。
- call 是 把第二个及以后的参数作为f方法的实参传进去
而bind 虽说也是获取第二个及以后的参数用于之后方法的执行,但是f_Extend中传入的实参则是在bind中传入参数的基础上往后排的。
function f(a,b,c){
console.log(a,b,c);
}
f.call(null, 'a'); // a undefined undefined
var f_Extend = f.bind(null,"extend_A");
f_Extend('a'); // extend_A a undefined
立即执行函数中无法赋值
现象如下,不知原因
// 使用立即执行函数
(function c () {
console.log(c); // Function c
c = 1000;
console.log(c); // Function c
})();
// 使用普通函数调用
function c () {
console.log(c); // Function c
c = 1000;
console.log(c); // 1000
};
c();
生成一个范围内的随机数
// Getting a random number between 0 and 1, inclusive
function getRandom() {
return Math.random();
}
// Getting a random number between two values
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// Getting a random integer between two values
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}