js学习进阶中-bind()方法

有次面试遇到的,也是没说清楚具体的作用,感觉自己现在还是没有深刻的理解!

bind():绑定事件类型和处理函数到DOM element(父元素上)

live():绑定事件到根节点上,(document上)
Delegate(): 可动态添加事件,绑定到你指定的元素节点

下面就bind()方法做一个例子实验:(已测试)

window.onload = function(){
window.name = "window";

var newObject = {
name : "object",

sayGreeting : function(){
alert("now this is easy"+" "+this.name);
nestedGreeting = function (greeting){
alert(greeting+" "+this.name);
}.bind(this);

nestedGreeting("hello");
}
};

newObject.sayGreeting("hello");
}

这个程序的输出:

now this is easy object

hello object

当去掉红色部分bind()方法时输出第二个弹窗:hello window(想一下原因)

前面说过bind()方法绑定到父元素,也就是对象newObject上,this指的就是父类name值是object

如果去掉,嵌套函数nestedGreeting()对象的内部函数分离了,函数作用域变成了窗口对象的属性,name值为window

对于this的引用作用域没搞清楚,不知道到底作用哪个,有的说是就近,那这个例子中this就近谁呢,输出的怎么不一样,有大神能简单明了的说一下,不胜感激!!

最后提供一个页面倒计时展示bind():

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style type="text/css">
#item {
font-size: 72pt;
margin: 70px auto;
width: 100px;
}
</style>
</head>
<body>
<div id = "item">
10
</div>
<script>
var theCounter = new Counter("item",10,0);
theCounter.countDown();

function Counter(id,start,finish){
this.count = this.start = start;
this.finish = finish;
this.id = id;
this.countDown = function (){
if(this.count ==this.finish){
this.countDown = null;
return;
}
document.getElementById(this.id).innerHTML = this.count--;
setTimeout(this.countDown.bind(this),1000);
}
}
</script>
</body>
</html>

好绕,没怎么明白this的用法!!!

 

posted on   hboot  阅读(6822)  评论(3编辑  收藏  举报

编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示