JavaScript中改变this指向callapplybind方法

    科技2025-07-21  8

    实例

    <script> //call和apply,都是可以改变this的指向 /*var obj1 = { width: 30, height: 50, getArear: function() { console.log(this.width*this.height); }, getCube: function(w,h,l){ console.log(this.name+ "体积为"+ w*h*l); } } obj1.getArear(); var obj2 = { width: 20, height: 40, name:"obj2" } var obj3 = { width:20, height:40, name:"obj3" } /!*obj2.__proto__ = obj1; obj2.getArear();*!/ console.log(obj2); obj1.getArear.call(obj2);//使用obj2替换了obj1中的getArear中的this obj1.getCube(3,4,5); obj1.getCube.call(obj2,2,3,4);//如果有参数的话则直接将参数写在后面的参数列表 obj1.getCube.apply(obj3, [2,5,8]);//apply方法和call方法唯一区别在于参数的写法,apply必须将参数写成数组的写法 //bind()方法,将生成一个新的函数,该函数也可以改变其中this指向,必须执行才可以 obj1.getCube.bind(obj3, 2,5,10)();//参数是按照Call的写法 var f = obj1.getCube.bind(obj2, 4,5,8); f();*/ //------实例 function Body(weight){ this.weight = weight; } function Head(hairColor){ this.hairColor = hairColor; this.changeHairColor = function(color){ this.hairColor = color; } } function Arms(armsLen){ this.armsLen = armsLen; } function Person(obj){ this.name = obj.name; Body.call(this, obj.weight); Head.call(this, obj.hairColor); Arms.call(this, obj.armsLen); this.eat = function(){ console.log(this.name + " is eating") this.weight++; console.log(this.weight); } } var p1 = new Person({ name:"张三", weight:100, hairColor:"red", armsLen:60 }) console.log(p1); p1.eat(); p1.changeHairColor("black"); console.log(p1); </script>
    Processed: 0.048, SQL: 8