本周学习知识

1.typeof 操作符

<p> typeof 操作符返回变量或表达式的类型。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 
    typeof "john" + "<br>" + 
    typeof 3.14 + "<br>" +
    typeof false + "<br>" +
    typeof [1,2,3,4] + "<br>" +
    typeof {name:'john', age:34};
</script>

2. this 关键字:this 不是固定不变的,它会随着执行环境的改变而改变。

this 的多种指向:

  •  1、在对象方法中, this 指向调用它所在方法的对象。
  •  2、单独使用 this,它指向全局(Global)对象。
  •  3、函数使用中,this 指向函数的所属者。
  •  4、严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
  •  5、在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。
  •  6、apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。

方法中的 this:在对象方法中, this 指向调用它所在方法的对象。

<p id="demo"></p>

<script>
// 创建一个对象
var person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// 显示对象的数据
document.getElementById("demo").innerHTML = person.fullName();
</script>

单独使用 this:单独使用 this,则它指向全局(Global)对象。

<p id="demo"></p>

<script>
var x = this;
document.getElementById("demo").innerHTML = x;
</script>

函数中使用 this(默认):在函数中,函数的所属者默认绑定到 this 上。

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
  return this;
}
</script>

函数中使用 this(严格模式):严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined

<p id="demo"></p>

<script>
"use strict";
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
  return this;
}
</script>

事件中的 this:this 指向了接收事件的 HTML 元素

<button οnclick="this.style.display='none'">点我后我就消失了</button>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值