js中的call()方法的使用实例

xiaoxiao2021-02-28  83

<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>call方法</title> <script type="text/javascript" src="jquery.js"></script> </head> <body> <script> $(document).ready(function(){ }) $().ready(function(){ //do something }) //参考:http://uule.iteye.com/blog/1158829 $(function(){ //------------1.常例-------------- function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1);//4 //---------------常例(1)-------------------- function add1(a,b) { //this(a,b); alert(a+b); } function sub1(a,b) { this(a,b); alert(a-b); } add1.call(sub1,3,1); //弹出4 //---------------常例(2)-------------------- function add2(a,b) { this(a,b); alert(a+b); } function sub2(a,b) { // this(a,b); alert(a-b); } add2.call(sub2,3,1); //依次弹出2和4,add2的this被替换指向sub2 //----------2.------------------------- function Animal(){ this.name = "Animal"; this.showName = function(){ alert(this.name); } } function Cat(){ this.name = "Cat"; } var animal = new Animal(); var cat = new Cat(); //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。 animal.showName.call(cat,",fw45tg354,'"); //Cat,此处call方法的第二个参数字符串可为任意的输出结果认为Cat //animal.showName.apply(cat,[]);//Cat //----------------3.实现继承----------------------------- function Animal1(name){ this.name = name; this.showName = function(){ alert(this.name); } } function Cat1(name){ Animal1.call(this, name); } // Cat1.prototype = new Animal1(); var cat1 = new Cat1("Black Cat"); cat1.showName();//Black Cat alert("是此类型?:"+cat1 instanceof Animal1); //false //-----------4.多重继承---------------------------- function Class10() { this.showSub = function(a,b) { alert(a-b); } } function Class11() { this.showAdd = function(a,b) { alert(a+b); } } function Class2() { Class10.call(this); Class11.call(this,6,2); } var c2 = new Class2(); c2.showSub(8,3);//5 c2.showAdd(6,2);//8 }) //---------5.使用call方法调用匿名函数--------------------- var animals = [ {species: 'Lion', name: 'King'}, {species: 'Whale', name: 'Fail'} ]; for (var i = 0; i < animals.length; i++) { (function (i) { this.print = function () { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); //#0 Lion: King //#1 Whale: Fail } //---------6.使用call方法调用函数并且指定上下文的'this'------------- //在下面的例子中,当调用 greet 方法的时候,该方法的 this 值会绑定到 i 对象。 function greet() { var reply = [this.person, 'Is An Awesome', this.role].join(' '); console.log(reply); } var i = { person: 'Douglas Crockford', role: 'Javascript Developer' }; greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer </script> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-79491.html

最新回复(0)