bind() 方法會創建一個新函數。當這個新函數被調用時,bind() 的第一個
參數將作為它運行時的 this,之后的一序列參數將會在傳遞的實參前傳入
作為它的參數。(來自于 MDN )
bind 功能:
1 返回一個函數
2 可以傳入參數
關于指定 this 的指向,我們可以使用 call 或者 apply 實現
但是在這個寫法中,我們直接將 fBound.prototype = this.prototype,我們
直接修改 fBound.prototype 的時候,也會直接修改綁定函數的 prototype。
這個時候,我們可以通過一個空函數來進行中轉
測試
~~~
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind2(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin
~~~
實現代碼
~~~
Function.prototype.bind2 = function(context) {
var that = this;
var args = Array.prototype.slice.call(arguments,1);
var fn = function(){}
var result = function() {
var bindArgs = Array.prototype.slice.call(arguments);
that.apply(this instanceof result ? this : context,args.concat(bindArgs));
}
fn.prototype = this.prototype;
result.prototype = Fn.prototype;
return result;
}
~~~
- 筆記內容來源
- 你不知道的JavaScript上
- vue
- 環境搭建
- node和npm安裝配置
- 安裝vue-cli并初始化vue項目
- 安裝配置elementUI
- vuex安裝配置
- axios安裝配置
- main.js
- vue基礎入門
- vue-router介紹
- vuex
- vue 原理學習源碼學習
- js正則處理v-bind和語法
- 雙向綁定
- 虛擬dom
- mvvm和render函數
- vue工作項目筆記
- elementUI 表格分頁多選記憶功能
- elementUI表格展開一行
- keepAlive
- vue整合ckeditor5
- this.$router.push 內打開新窗口
- java修改上傳圖片的權限
- 兼容ie11
- 生成二維碼
- base64圖片下載(兼容IE10)
- vue新手引導程序intro.js
- vue插件 devtools
- vue刷新當前頁面
- vue 錨點導航
- axios
- axios與springmvc
- vue-cli 3搭建vue
- git
- git常用命令
- 正則表達式
- 實例demo
- 1
- 新手引導頁
- 純css3從左顯示下劃線動畫導航菜單
- 純css3從中間顯示下劃線動畫導航菜單
- css顯示密碼
- 倒計時時鐘
- 星星評分
- 按鈕懸停效果
- 步驟條
- css動畫按鈕
- input標題獲得焦點上移
- css圖片放大
- css鏡像導航欄
- js
- 通信
- for in 和 for of
- 前端安全問題
- Promise
- 掘金冴羽學習筆記
- 模擬call
- 模擬bind
- 閉包
- 1 作用域
- 2 執行上下文棧
- 3 變量對象
- 4 作用域鏈
- 5 this
- 面向對象
- 基礎知識點
- 渲染機制
- 其他
- 判斷是否為數組
- http
- css
- 基礎知識
- css陰影