Js中的this

this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用;
以下分为多重情况 说明this的在不同的作用域里 指向也是不同的

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>

<body>
<script>
//一、全局的this在浏览器下 等于 window
/*
console.log(this.document === document);//true
console.log(this === window);//true
this.a = 31;
console.log(window.a);//31


//二、一般函数的this(浏览器)
function f1(){
    return this;
    }
    
    f1() === window;  //true,global object

//严格模式下
function f2(){
    "use strict";
    return this;
    }
    f2() ===undefined;//true
    
    
//三、作为对象方法的函数的this   o.f();
var o={//对象字面量o
    prop :21,//prop属性
    f:function(){//函数作为对象的属性 叫做对象.方法
        return this.prop;
        }
    };
    console.log(o.f());//21

var p={pro:22};
function independent(){//直接调用independent this指向浏览器window对象
    return this.pro; 
    }
    p.f=independent;
    console.log(p.f());
//四、原型链上的this   
var  o={f:function(){return this.a +this.b;}};
var p = Object.create(o);
p.a =1;
p.b =2;
console.log(p.f()); //3

//五、get/set方法的this
function mod(){
    return Math.sqrt(this.re *this.re +this.im*this.im);
    }
var o={
    re:1,
    im:-1,
    get ph(){
        return Math.atan2(this.re,this.im)
        }
    };  
Object.defineProperty(o,'mod',{
    get:mod,enumerable:true,configurable:true
    }); 
console.log(o.mod,o.ph);//1.4142135623730951 2.356194490192345

//六。构造器中的this
function MyClass(){
    this.a = 23;
    }
var o = new MyClass();//实例化一个空对象o 原型链指向MyClass
console.log(o.a);//23 当对象只有基本类型时 会把基本类型作为返回值

function C1(){
    this.a = 23;
    return{a:22};//当对象有返回方法 会吧方法作为优先返回值
    }
o1 = new C1();
console.log(o1.a);//22


//七、call/apply方法与this
function add(c,d){
    return this.a +this.b +c +d;
    }   
var o={a:1,b:2};
console.log(add.call(o,2,3));   //8  .call(o,arg1,arg2..)
console.log(add.apply(o,[4,5]));//12 .apply(o,[arg1,arg2..]);

function bar(){
    console.log(Object.prototype.toString.call(this));//[object Number]
    }   
bar.call(7);
*/

//八、bind方法与this
function f(){
    return this.a;
    }   
var g= f.bind({a:'test'});
console.log(g());               //test

var o={a:21,f:f,g:g};
console.log(o.f(),o.g());       //21 "test"
</script>
</body>
</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容