2015-05-19 29 views
0

我想了解一個Chrome擴展,它顯示html頁面中任何選定元素的xpath。 我遇到了這個我無法理解的代碼。javascript類中的變量定義

'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; 

綁定函數究竟在幹什麼? 調用綁定時使用的方法未在代碼中的任何位置定義。

+0

這看起來像一個問題http://codereview.stackexchange.com/ –

+1

@NickVolynkin這將是[封閉作爲離題](http://meta.codereview.stackexchange.com/questions/3649/my - 問題是關閉的,因爲它是關閉的主題,什麼是我的選擇/ 3654#3654)在代碼審查。 – mjolka

+0

好的,不好的建議) –

回答

0

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

返回一個新的函數,調用它時,都會有這樣等於thisArg,以參數1等於第一個參數,第二個參數等於PARAM2等

我們主要使用Bind()方法來調用一個明確設置了該值的函數。換言之,bind()允許我們在調用函數或方法時輕鬆設置將綁定到哪個特定對象。

+0

這可能是一個有用的參考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Teepeemm