日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

改变 this 指向的 call 和 apply

發布時間:2025/3/12 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 改变 this 指向的 call 和 apply 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、call 方法
基本用法

function test() {console.log('hello world'); } test(); // hello world test.call(); // hello world // test() ==> test.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 需要傳一個 arguments 實參列表
  • [].slice.call(arguments) -- 能將具有 length 屬性的對象轉換為數組

    三、總結

    call / apply 都是改變 this 指向,區別就是傳參列表不同

    總結

    以上是生活随笔為你收集整理的改变 this 指向的 call 和 apply的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。