• this
    • this几种不停的使用场景

    this

    • this 要在执行时才能确认值,定义时无法确认值
    1. var a = {
    2. name:'A',
    3. fn:function(){
    4. console.log(this.name);
    5. }
    6. }
    7. a.fn() //this === A
    8. a.fn.call({name:'B'}) //this === {name:'B'}
    9. var fn1 = a.fn;
    10. fn1() //this === window
    • 作为构造函数执行
    • 作为对象属性执行
    • 作为普通函数执行
    • call apply bind
    1. function Foo(name){
    2. this.name = name;
    3. }
    4. var f = new Foo('zhangsan');
    5. var obj = {
    6. name:'A',
    7. printName:function(){
    8. console.log(this.name);
    9. }
    10. }
    11. obj.printName()
    12. function fn(){
    13. console.log(this);
    14. }
    15. fn()
    16. // call apply bind
    17. function fn1(name) {
    18. alert(name);
    19. console.log(this);
    20. }
    21. fn1.call({x:100},'zhangsan',20);
    22. // bind
    23. var fn2 = function fn2(name) {
    24. alert(name);
    25. console.log(this);
    26. }.bind({y:200});
    27. fn2('zhangsan',20);

    this几种不停的使用场景

    • 作为构造函数执行
    • 作为对象属性执行
    • 作为普通函数执行
    • call apply bind
    1. function Foo(name){
    2. this.name = name;
    3. }
    4. var f = new Foo('zhangsan');
    5. var obj = {
    6. name:'A',
    7. printName:function(){
    8. console.log(this.name);
    9. }
    10. }
    11. obj.printName()
    12. function fn(){
    13. console.log(this);
    14. }
    15. fn()
    16. // call apply bind
    17. function fn1(name) {
    18. alert(name);
    19. console.log(this);
    20. }
    21. fn1.call({x:100},'zhangsan',20);
    22. // bind
    23. var fn2 = function fn2(name) {
    24. alert(name);
    25. console.log(this);
    26. }.bind({y:200});
    27. fn2('zhangsan',20);