New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第55天 写出4个使用this的典型例子 #217
Comments
|
function Contructor(name){
this.name = name
}
setTimeout(function(){}.bind(this),1000) |
react中constructor中, this.handleClick=this.handleClick.bind(this); |
补充调用上下文 const ctx = {
a:1,
test(){
console.log(this.a);
}
};
ctx.test(); |
var b = {
a: function() {
console.log(this);
}
}
b.a();
// this is b
b.a.call(this); // this is window
function B() {
this.a = function() {console.log(this.b)},
this.b = 1
}
let b = new B();
b.a();
// this is b object;
var a = 1;
this.a; |
1⃣️ 全局 this 是 window |
构造函数function Anmai(params) {
this.params = params
} call,bind,applycall 求最值let maxNum = Math.max.call(this,5,45,120,-1)
let minNum = Math.min.call(this,5,45,120,-1)
console.log(maxNum ,minNum); apply 求最值const nums = [5,45,120,-1]
let maxNum = Math.max.apply(this,nums)
let minNum = Math.min.apply(this,nums)
console.log(maxNum ,minNum); bind 使用例子
this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象
var Module = {
x: 81,
getX: function() { return this.x; }
};
console.log(Module.getX());// 81
var retrieveX = Module.getX;
console.log(retrieveX());
// 返回 9 - 因为函数是在全局作用域中调用的
// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(Module);
console.log(boundGetX()) // 81 |
btn.onclick(function() {
console.log(this.className)
}); |
|
普通函数和定时器,this是window |
// 全局作用域 |
这是来自QQ邮箱的假期自动回复邮件。
辛苦了,邮件已经收到~~
|
(1)在html元素事件属性中使用,如 (2)构造函数 function Animal(name, color) { This.name = name; this.color = color; } (3) Var btn = document.getElementById(“text”); Btn.onclick = function() { Alert(this.value); //此处的this是按钮元素 } (4)CSS expression表达式中使用this关键字
|
这是来自QQ邮箱的假期自动回复邮件。
辛苦了,邮件已经收到~~
|
第55天 写出4个使用this的典型例子
The text was updated successfully, but these errors were encountered: