webveuje/js/lx/callapply.md
2021-03-23 10:58:10 +08:00

1.9 KiB
Raw Blame History

  1.  window.color = 'red';
     document.color = 'yellow';
    
     var s1 = {color: 'blue' };
     function changeColor(){
         console.log(this.color);
     }
    
     changeColor.call();         //red (默认传递参数)
     changeColor.call(window);   //red
     changeColor.call(document); //yellow
     changeColor.call(this);     //red
     changeColor.call(s1);       //blue
    

2 var Pet = { words : '...', speak : function (say) { console.log(say + ''+ this.words) } } Pet.speak('Speak'); // 结果Speak...

var Dog = {
    words:'Wang'
}

//将this的指向改变成了Dog
Pet.speak.call(Dog, 'Speak'); //结果: SpeakWang

3
用 apply重写上面两个函数

4 function add(c,d){ return this.a + this.b + c + d; }

var s = {a:1, b:2};
console.log(add.call(s,3,4)); // 1+2+3+4 = 10
console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14 

5.画出原型链 //游戏--->王者---->小乔---->花嫁

6 function C1(name) { if (name) { this.name = name; } }

function C2(name) { this.name = name; }

function C3(name) { this.name = name || 'join'; } C1.prototype.name = 'Tom'; C2.prototype.name = 'Tom'; C3.prototype.name = 'Tom'; alert((new C1().name) + (new C2().name) + (new C3().name));

7 function Fn(num) { this.x = this.y = num; } Fn.prototype = { x: 20, sum: function () { console.log(this.x + this.y); } }; let f = new Fn(10); console.log(f.sum === Fn.prototype.sum); f.sum(); Fn.prototype.sum(); console.log(f.constructor);

8 var print=function(){alert(1);} function Fn() { print=function(){alert(2);} return this; } function print(){alert(3);} Fn.prototype.print=function(){alert(4);} Fn.print=function(){alert(5);}

print(); Fn.print(); Fn().print(); new Fn.print(); new Fn().print();