java 中的this就是 类的一个实例,就是对象
public class Test{
private String str;
private List linkedList;
//this对象
public Test this;
public void test(Test this, String str, List linkedList){
this.linkedList = linkedList;
this.str = str;
}
public String add(Test this, String str, String result){
return this.str + result;
}
public static void main(String[] args) {
Test test1 = new Test();
}
}
js中的this永远指向 函数对象的上级对象(函数也是对象)
如果是全局函数对象,那么this指向window
-
如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window,非严格模式为undefined。
-
如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
-
如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象。
var operation = {
add: function (num1, num2) {
console.log(num1 + num2);
// this 始终指向函数对象的上级对象
return this; //返回当前函数对象的上级对象operation
},
subtract: function (num1, num2) {
console.log(num1 - num2);
return this;
},
'@': function () {
console.log('@');
},
key: function () {
// body...
}
};
operation.add(1, 2).subtract(2, 1);
如下:廖雪峰js教程中的例子
为什么getAge()返回NaN?
因为在xiaoming对象外部调用函数,this指向window,而windo并没有birth,所以返回NaN
function getAge() {
var y = new Date().getFullYear();
return y - this.birth;
}
var xiaoming = {
name: '小明',
birth: 1990,
age: getAge
};
xiaoming.age(); // 25, 正常结果
getAge(); // NaN
如下:
this还可以改变全局变量的值
function test(){
this.x = 1; //this指向全局变量 ==> window.x=1
alert(this.x);
}
test();// 1
var x = 1;
function test(){
this.x = 0 //改变了 全局变量 x 值
}
test();
alert(x); //0
下面的函数最后返回 3 , 这两个嵌套函数都是属于 window对象,函数虽然是对象,但跟正真的对象还是有差别
不管什么函数(嵌套与否),都属于同一个对象
var name = '3'
function test () {
var name = '1'
function abc() {
var name = '2'
return this.name //此时的this指向window
}
return abc()
}
test() // 3
下面不知道为什么
function test () {
function abc() {
var name = '2'
}
return this.name //有 this可以输出
}
test() // undefined
function test () {
function abc() {
var name = '2'
}
return name
}
test() // 报错
自执行的匿名函数形成独立作用域
//生成十个按钮 每个按点击的时候弹出1 - 10
var i = 0;
for (i = 1; i <= 10; i ++) {
(function(i) {
var btn = document.createElement('button');
btn.innerText = i;
btn.onclick = function() {
alert(i)
};
document.body.appendChild(btn);
})(i);
}
//以下不管点哪个按钮都会输出 11
var i = 0;
for (i = 1; i <= 10; i ++) {
// (function(i) {
var btn = document.createElement('button');
btn.innerText = i;
btn.onclick = function() {
alert(i)
};
document.body.appendChild(btn);
// })(i);
}
// 下面是正常的
for (let i = 1; i <= 10; i ++) {
var btn = document.createElement('button');
btn.innerText = i;
btn.onclick = function() {
alert(i)
};
document.body.appendChild(btn);
}