事件处理,延伸学习 function bind(Day 8)

<button onClick={this.deleteRow.bind(this, 'id')}>Delete Row</button>

在前一篇里我们会看到事件传递参数里写到 bind 这样的语法,但为什麽要用 bind?
什麽是 bind? 再看 bind 前要先看 this 是什麽

看 W3S 学习 this

  1. 如果没有任何东西包,this 指向浏览器 (BOM) 最上层 global 的 window
  2. 在 Class 的方法里面,this 指令 Class 物件本身
  3. 在一般函数里,this 也指向浏览器 (BOM) 最上层 global 的 window
  4. 严格模式的函数里,this 是 undefind
  5. 在 event 里,this 指向该 element
  6. 搭配 call 或 apply ,this 可以指向 call 或 apply 所绑定的物件

因为 5.。 event 本身的 this 会指向元素本身,所以必须只用 bind 去定义 this 要指向什麽物件,也就为什麽会有 this.handleClick = this.handleClick.bind(this) 的使用,让 this 可以绑定到 Class component 本身。

bind 语法与其他例子

语法

fun.bind(thisArg[, arg1[, arg2[, ...]]])

自己练习写一个简单的 bind(按F12,浏览器打开 console,贴上下面程序码)

var element = document.querySelector(".header__logo");

var user = {
    firstname: 'Hu',
    lastname: 'Jim',
    greeting: function(e){
       e.preventDefault();
       alert('My name is ' + this.firstname + this.lastname);
    }
};

user.greeting = user.greeting.bind(user);

element.addEventListener('click', user.greeting);

点击iT邦帮忙Logo测试画面

以上今天。

参考资料:
MDN bind
understanding-javascript-function-prototype-bind
W3S keyword this


<<:  系统弱点扫描工具-Tenable Nessus(下)

>>:  每日挑战,从Javascript面试题目了解一些你可能忽略的概念 - Day7

[Day-22] 呼叫自订函式小练习

上次练习完了自订函式的基础 今天就要来练习相关题目罗~ 题目: 1.计算:键盘输入任一整数a,计算2...

Day-28 说明什麽是 Migration ?

Rails 里常常出现的 Migration 又是什麽呢?大家常常误解他,让我们来认识一下他吧。 ...

Day 27 [Python ML、资料清理] 处理资料中的时间

设定环境 首先我们需要读取libraries跟dataset,我们将会使用一个dataset是包含在...

Windows 安装 PHP IMagick

根据很多网路上的教学,需要两个主要档案 php_imagick.xxx.zip ImageMagic...

Day62 (Vue)

1.computed & Watch Part_1 > Lab_Binding >...