面向对象语言中 this 表示当前对象的一个引用。
但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
在方法中,this 表示该方法所属的对象。
如果单独使用,this 表示全局对象。
在函数中,this 表示全局对象。
在函数中,在严格模式下,this 是未定义的(undefined)。
在事件中,this 表示接收事件的元素。
类似 call() 和 apply() 方法可以将 this 引用到任何对象。
在对象方法中, this 指向调用它所在方法的对象。
在上面一个实例中,this 表示 person 对象。
fullName 方法所属的对象就是 person。
单独使用 this,则它指向全局(Global)对象。
在浏览器中,window 就是该全局对象为 [object Window]:
如果单独使用,this 也是指向全局(Global)对象。
在函数中,函数的所属者默认绑定到 this 上。
在浏览器中,window 就是该全局对象为 [object Window]:
严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:
下面实例中,this 是 person 对象,person 对象是函数的所有者:
* this.firstName 表示 this (person) 对象的 firstName 属性。
在 JavaScript 中函数也是对象,对象则有方法,apply 和 call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。
在下面实例中,当我们使用 person2 作为参数来调用 person.fullName 方法时, this 将指向 person2, 即便它是 person的方法。
相信很多jquery使用者在都很熟悉this和$(this),但是二者到底有什么区别呢,下面我们就利用代码谈谈二者的区别。
请看下图中代码 saveRule(this)方法中的this
obj就是this。
测试结果如下图:
总结:this就是一个html元素,他没有parent方法,$(this)是一个jquery对象,他有parent方法。
原文:https://dev.to/bhagatparwinder/arrow-function-basics-34cm
箭头函数是在 ES6 引入的,相对于函数表达式来说是一种更简洁的方式。
箭头函数名称的来源是因为使用了 =>。
const functionName = (arg1, arg2, ... argN) => {
return value;
}
const multiply = (a, b) => {
return a * b;
}
console.log(multiply(7, 8)); // 56
console.log(multiply(3, 2)); // 6
const square = x => {
return x * x;
}
console.log(square(2)); // 4
console.log(square(7)); // 49
这个情形的唯一陷阱是当只有一个参数且需要解构时:
const foo = ({name = "New User"}) => name;
console.log(foo({})); // New User
console.log(foo({name: "Parwinder"})); // Parwinder
const greeting = () => {
return "Hello World!";
}
console.log(greeting()); // Hello World!
const greeting = () => "Hello World!";
console.log(greeting()); // Hello World
现在我们知道了所有的关键特点,让我们来重写获取正方形的面积:
const square = x => x * x;
console.log(square(4)); // 16
JavaScript 中的 this 关键字是执行上下文的一个属性,它可能是全局的、函数内的或者是 eval 中的。对于普通的函数,this 会根据调用它方式不同而变化。
我们使用这种行为已经很久了,以至于大多数JavaScript开发者都已经习惯了。
function foo() {
return this;
};
console.log(foo()); // window object in a browser, global object for node execution
function Order(main, side, dessert) {
this.main = main;
this.side = side;
this.dessert = dessert;
this.order = function () {
return `I will have ${this.main} with ${this.side} and finish off with a ${this.dessert}`;
}
}
const newOrder = new Order("sushi", "soup", "yogurt");
console.log(newOrder.order());
// I will have sushi with soup and finish off with a yogurt
const myObject = {
main: "butter chicken",
side: "rice",
dessert: "ice cream",
order: function () {
return `I will have ${this.main} with ${this.side} and finish off with ${this.dessert}`;
}
}
console.log(myObject.order());
// I will have butter chicken with rice and finish off with ice cream
上面的例子中,this 指向 myObject,可以获取它上面的属性。
"use strict";
function foo() {
return this;
};
console.log(foo() === undefined); // true
*请认真填写需求信息,我们会在24小时内与您取得联系。