js 随机记录

contains()

用来查看 dom 元素的包含关系;如果 js 要判断数组的包含关系,建议用 indexof

var Arrays = ['11','22','33'];
var Array ='11';
console.log(Arrays.indexOf(Array) >= 0); // true

parentNode

获取 dom 元素父节点

document.getElementById("item").parentNode; // 获取 id 为 item 元素的父节点

bind()、 call()、apply()

1、都是用来改变函数的this对象的指向的。
2、第一个参数都是this要指向的对象。
3、都可以利用后续参数传参。

bind(): 将函数绑定到某个对象;
bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值,例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj;

context(
    function() {
        return this.greeting + ', ' + this.name + '!'; 
    }, 
    {
        name: 'Rebecca', 
        greeting: 'Yo' 
    }
)

function context(fn, obj) {
    console.log(fn.bind(obj)()); // Yo, Rebecca!
}

call() 方法分别接受参数。

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway");

apply() 方法接受数组形式的参数。

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
function partial(fn, str1, str2) {
    return function result(str3) {
        console.log('bind: ', fn.bind(this, str1, str2, str3)());  // bind:  Hello, Ellie!!!
        console.log('call: ', fn.call(this, str1, str2, str3)); // call:  Hello, Ellie!!!
        console.log('apply: ', fn.apply(this, [str1, str2, str3])); // apply:  Hello, Ellie!!!
    }
}

var sayIt = function(greeting, name, punctuation) {
    return greeting + ', ' + name + (punctuation || '!'); 
};  
partial(sayIt, 'Hello', 'Ellie')('!!!');

总结: bind 方法不能直接对函数进行调用, 返回的还会是一个函数, 需要在后面加括号; 如: f.bind(obj)(); call和apply可以对函数的直接调用;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值