标签:因此 click 构造 document cto 设定 script his function
window是js中的全局对象,我们创建的变量实际上是给window添加属性
this的最终指向的是那个调用它的对象
<script> function foo(){ var name=‘ruby‘; alert(this.name) //undefined } foo(); console.log(this); //window </script> window中没name这个属性,因此找不到
<script> var name=‘jerd‘; function foo(){ var name=‘ruby‘; alert(this.name) //jerd } foo(); console.log(this); //window </script>
var person = { run: function () { console.log(this) //指向person这个对象 } } person.run()
<script> var name=‘jerd‘; var people= { user:"ruby", fn:function(){ console.log(this.user); //this指people这个对象 } }; window.people.fn() //ruby </script>
<script> var people = { name:‘jerd‘, obj:{ fn:function(){ alert(this.name); } } }; people.obj.fn(); //undefined 此时this指向对象b。b中无a属性,因此值为undefined </script>
赋值情况
<script> var people = { name:‘jerd‘, obj:{ fn:function(){ alert(this); //this指向windonw } } }; var obj1=people.obj.fn; obj1(); </script> this永远指向的是最后调用它的对象,函数fn是被对象obj1所引用, 但是在将fn赋值给变量obj1的时候并没有执行所以最终指向的是window
var btn = document.querySelector("button") btn.onclick = function () { console.log(this) // btn }
function Person(){ console.log(this)//window } Person()
function Person(){ console.log(this)//people } var people = new Person()
<script> var name=‘jerd‘; function Foo(){ this.name=‘ruby‘; this.func=function () { var name="zhao"; alert(this.name) } } var obj= new Foo(); obj.func() </script> #ruby
<script> var name=‘jerd‘; function Foo(){ this.name=‘ruby‘; this.func=function () { console.log(this) //Foo (function () { alert(this.name) //window })() } } var obj= new Foo(); obj.func() </script>
标签:因此 click 构造 document cto 设定 script his function
原文地址:https://www.cnblogs.com/zgf-666/p/9249828.html