改变 this 指向的 call 和 apply
生活随笔
收集整理的這篇文章主要介紹了
改变 this 指向的 call 和 apply
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、call 方法
基本用法
其實就是借用別人的方法,來實現自己的功能
function Person(name, age) {// this == objthis.name = name;this.age = age; }var obj = {};var person = new Person(); Person.call(obj, 'mary', 18); // 讓 obj 也擁有構造函數的方法call 的根本作用就是改變 this 指向,第一個參數就是 this 的指向
小案例
function Student(name, age, sex) {this.name = name;this.age = age;this.sex = sex; }function Color(red, blue, pink) {this.red = red;this.blue = blue;this.pink = pink; }function Model(height, width, len) {this.height = height;this.width = width;this.len = len; }function Car(name, age, sex, red, blue, pink, height, width, len) {// var this = {// // };Student.call(this, name, age, sex);Color.call(this, red, blue, pink);Model.call(this, height, width, len); }var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);二、apply 方法
function Student(name, age, sex) {this.name = name;this.age = age;this.sex = sex; }function Color(red, blue, pink) {this.red = red;this.blue = blue;this.pink = pink; }function Model(height, width, len) {this.height = height;this.width = width;this.len = len; }function Car(name, age, sex, red, blue, pink, height, width, len) {// var this = {// // };Student.apply(this, [name, age, sex]);Color.apply(this, [red, blue, pink]);Model.call(this, height, width, len); }var car = new Car('mary', 18, 'female', 'red', 'blue', 'pink', 175, 75, 175);三、總結
call / apply 都是改變 this 指向,區別就是傳參列表不同
總結
以上是生活随笔為你收集整理的改变 this 指向的 call 和 apply的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一些常规形几何形状的绘制和效果填充(三)
- 下一篇: 绘制颜色渐变三角形