function a(){
console.log(this); //输出函数a中的this对象
}
function b(){} //定义函数b
var obj = {name:'onepixel'}; //定义对象obj
a.call(); //window
a.call(null); //window
a.call(undefined);//window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b);// function b(){}
a.call(obj); //Object
var a = {
name:'onepixel', //定义a的属性
say:function(){ //定义a的方法
console.log("Hi,I'm function a!");
}
};
function b(name){
console.log("Post params: "+ name);
console.log("I'm "+ this.name);
this.say();
}
b.call(a,'test');
>>
Post params: test
I'm onepixel
I'm function a!
function b(x,y,z){
console.log(x,y,z);
}
b.apply(null,[1,2,3]); // 1 2 3
var obj = {name:'onepixel'};
/**
* 给document添加click事件监听,并绑定onClick函数
* 通过bind方法设置onClick的this为obj,并传递参数p1,p2
*/
document.addEventListener('click',onClick.bind(obj,'p1','p2'),false);
//当点击网页时触发并执行
function onClick(a,b){
console.log(
this.name, //onepixel
a, //p1
b //p2
)
}
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this, //this在这里指向的是目标函数
fBound = function () {
return fToBind.apply(
//如果外部执行var obj = new fBound(),则将obj作为最终的this,放弃使用oThis
this instanceof fToBind
? this //此时的this就是new出的obj
: oThis || this, //如果传递的oThis无效,就将fBound的调用者作为this
//将通过bind传递的参数和调用时传递的参数进行合并,并作为最终的参数传递
aArgs.concat(Array.prototype.slice.call(arguments)));
};
//将目标函数的原型对象拷贝到新函数中,因为目标函数有可能被当作构造函数使用
fBound.prototype = this.prototype;
//返回fBond的引用,由外部按需调用
return fBound;
};
}
function Animal(name,weight){
this.name = name;
this.weight = weight;
}
function Cat(){
Animal.call(this,'cat','50');
//Animal.apply(this,['cat','50']);
this.say = function(){
console.log("I am " + this.name+",my weight is " + this.weight);
}
}
var cat = new Cat();
cat.say();//I am cat,my weight is 50
function test(){
//检测arguments是否为Array的实例
console.log(
arguments instanceof Array, //false
Array.isArray(arguments) //false
);
//判断arguments是否有forEach方法
console.log(arguments.forEach); //undefined
// 将数组中的forEach应用到arguments上
Array.prototype.forEach.call(arguments,function(item){
console.log(item); // 1 2 3 4
});
}
test(1,2,3,4);
var arr = [2,3,1,5,4]; Math.max.apply(null,arr); // 5
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有