zoukankan      html  css  js  c++  java
  • 关于js的this上下文环境绑定

    javascript的this关键字很特别和actionscript2.0时期this指向是一样的,如果你以前是个actionscript2.0的coder那肯定是往事不堪回首。actionscript3.0以后this关键字就是指向类本身,而javascript至今还是未实现this始终指向类本身的功能。
    新版本的ECMAScript5中已经加入了bind函数以控制this关键字的绑定,但是在这之前最好还是自己实现bind函数,通过判断Function.prototype.bind是否支持来实现自己的bind函数,如果已经实现则使用浏览器原生支持的方法。
    1、简易的绑定this到某对象上

    if(!Function.prototype.bind){
    Function.prototype.bind = function(obj){
    var self = this;
    return function(){
    return self.apply(obj);
    }
    };
    }

    使用方法:

    var foo = {
    name:'foo';
    sayName: function(){
    console.log(this.name);
    }
    }
    foo.sayName.bind(foo);

    2、prototype框架使用的this绑定方法可传递参数

    if (!Function.bind) {
            Function.prototype.bind = function() {
                var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
                return function() {
                    return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
                };
            };
        };

    使用方法:

    func.bind(this, 1,2,3);//绑定并传递额外的参数1,2,3等

  • 相关阅读:
    驱动Makefile
    ioremap
    file结构体
    Python基础-语法知识
    企业运营对 DevOps 的「傲慢与偏见」
    漂亮得不像实力派!
    如何用 OneAPM 优化你的 Node.js 应用?
    全球说:要给 OneAlert 点100个赞
    DevOps 和技术债务偿还自动化
    PHP 性能分析与实验(二)——PHP 性能的微观分析
  • 原文地址:https://www.cnblogs.com/goody9807/p/2795204.html
Copyright © 2011-2022 走看看