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可以对函数的直接调用;