this指向 + 案例

this指向改变
        因为js 的特性,导致很多this指向并不如人意,js给我们提供了很多this指向改变的方法;
        this指向的改变我们一般都应用在面向对象的编程中
        
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
}
.phoph{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
z-index: 100;
 
}
.pgp{
position: absolute;
z-index: 1;
background: rgba(0,0,0,0.3);
width: 100%;
height: 100%;
 
}
.pop{
width: 300px;
height: 100px;
background: white;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
font-size: 40px;
z-index: 2;
margin: auto;
line-height: 100px;
text-align: center;
}
#btn{
width: 50px;
height: 30px;
margin: 20px 20px;
}
 
</style>
<body>
<button id="btn">按钮</button>
<div class="phoph">
<div class="pop">
<p>hello world</p>
</div>
<div class="pgp">
 
</div>
</div>
</body>
<script>
function Phoph(){}
Phoph.prototype.init = function(){
this.btn = document.querySelector("#btn");
this.phoph = document.querySelector(".phoph");
this.bindEvent();
}
Phoph.prototype.bindEvent = function(){
this.btn.onclick = this.show.bind(this);
this.phoph.onclick = this.hide.bind(this);
}
Phoph.prototype.show = function(){
this.phoph.style.display = "block";
}
Phoph.prototype.hide = function(){
this.phoph.style.display = "none";
}
 
 
var phoph = new Phoph();
phoph.init();
</script>
</html>
为了不让 函数嵌套 把事件处理函数提取出来;
 
this.btn === object;
onclick === 属性名
this.show === 一个函数的引用地址
 
object.proprety = function(){
    console.log(this);
}
object.proprety();
 
在面向对象编程之中 所有的函数的this指向必须指向当前的实例化对象
 
 
this指向的改变方案
 
1、call apply; ******在调用函数的时候改变this指向的
function foo (a,b){
    console.log(this , a,b);
}
window.foo();
foo.call({},1,2);
foo.apply({},[3,4])
 
 
call , apply 方法第一个参数是改变被调用的函数的this指向;
不同:
        call :第二个之后的实参和函数体内的形参一一对应;
        apply: 第二个参数是数组,数组的每一项和形参的每一项一一对应;
2.bind => ES5;
   在函数体上改变this的指向;
    在函数体创建的时候就规定好了函数的this指向从此不可变更;
    bind 方法是产生一个新函数的方法,所以bind方法规定必须给匿名函数使用;
 
var foo = function (a){
    console.log(this,a);
}.bind({},10);
foo(1000)
 
 
 

猜你喜欢

转载自www.cnblogs.com/TianPeng2/p/9991748.html