简体   繁体   English

javascript类中的变量定义

[英]Variable definition in javascript class

I am trying to understand a chrome extension which displays the xpath for any selected element in the html page. 我试图理解一个chrome扩展名,该扩展名显示html页面中任何选定元素的xpath。 I came across this code I wasn't able to understand. 我遇到了我无法理解的代码。

'use strict';

// Extension namespace.
var xh = xh || {};

xh.bind = function(object, method) {
  return function() {
    return method.apply(object, arguments);
  };
};
////////////////////////////////////////////////////////////////////////////////
// xh.Bar class definition

xh.Bar = function() {
  this.boundShowBar_ = xh.bind(this, this.showBar_);
  this.boundHandleRequest_ = xh.bind(this, this.handleRequest_);
  this.boundMouseMove_ = xh.bind(this, this.mouseMove_);
  this.boundKeyDown_ = xh.bind(this, this.keyDown_);

  chrome.extension.onMessage.addListener(this.boundHandleRequest_);

  this.barFrame_ = document.createElement('iframe');
  this.barFrame_.src = chrome.extension.getURL('bar.html');
  this.barFrame_.id = 'xh-bar';
  this.barFrame_.className = 'top';
  this.barFrame_.style.height = '0';

  // Temporarily make bar 'hidden' and add it to the DOM. Once the bar's html
  // has loaded, it will send us a message with its height, at which point we'll
  // set this.barHeightInPx_, remove it from the DOM, and make it 'visible'.
  // We'll add it back to the DOM on the first bar request.
  //this.barFrame_.style.visibility = 'hidden';
  document.body.appendChild(this.barFrame_);

  document.addEventListener('keydown', this.boundKeyDown_);
};

xh.Bar.prototype.active_ = false;
xh.Bar.prototype.barFrame_ = null;
xh.Bar.prototype.barHeightInPx_ = 0;
xh.Bar.prototype.currEl_ = null;
xh.Bar.prototype.boundHandleRequest_ = null;
xh.Bar.prototype.boundMouseMove_ = null;
xh.Bar.prototype.boundKeyDown_ = null;

What exactly is the bind function doing? 绑定函数到底在做什么? The methods used while calling bind are not defined anywhere in the code. 在代码中的任何地方都没有定义调用bind时使用的方法。

 bind(thisArg : Object, [param1 : Object, [param2 : Object, [...]]]) : Function 

Returns a new function that, when called, will have this equal to thisArg, the first parameter equal to param1, the second parameter equal to param2, etc. 返回一个新函数,该函数在调用时将等于thisArg,第一个参数等于param1,第二个参数等于param2,依此类推。

We use the Bind () method primarily to call a function with the this value set explicitly. 我们主要使用Bind()方法来调用显式设置了this值的函数。 It other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked. 换句话说,bind()允许我们轻松地设置在调用函数或方法时将哪个特定对象绑定到此对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM