2

我正在尝试修改插件(Pikaday)并添加我自己的一点功能。

该插件是使用原型系统构建的,我在其中添加了我的功能。

Pikaday.prototype = {

   //OTHER PARTS OF PLUGIN

  showYearPicker: function()
        {
            document.getElementsByClassName('pika-year-label').onclick=function(){
                console.log("asfd");
            }
        }, 

    //OTHER PARTS OF PLUGIN
}

return Pikaday;

我无法理解的是如何实际触发此方法。单击指定的元素不起作用。

有谁知道我如何将此功能作为插件的一部分包含在内?

如果有人感兴趣,完整的代码(减去我的添加)在这里。

4

1 回答 1

3

用简单的术语定义函数原型上的方法意味着您已经在对象上定义了一个方法,该方法将成为该函数所有实例的原型链的一个链接。

您可以将其视为该函数的每个实例的通用“父级”或“上方对象”。

因此,要使用您的方法,您必须实例化插件并在其上调用您的函数。

function Pikaday() {}

Pikaday.prototype = {

  showYearPicker: function() {
    console.log('called');
  }
}

let pikaday = new Pikaday();
pikaday.showYearPicker(); // <-- call the function on the prototype

这将做的是检查是否pikaday已经showYearPicker定义了它,因为它没有,它会沿着原型链向上并检查该对象是否有它,它确实如此。

换句话说,这本质上是 JS 引擎在幕后所做的:

let pikaday = new Pikaday();
pikaday.__proto__.showYearPicker();

请注意,这里的proto只是为了演示,它最近才在 ES6 中标准化以用于遗留目的,但是这种行为应该留给 JS 引擎(规范称为这个 proto 链接[[Prototype]])。

如果需要,访问原型的正确方法是使用Object.getPrototypeOf(在 +ES6 中,您可以使用语义更清晰的Reflect.getPrototypeOf

function Pikaday() {}

console.log(
  Object.getPrototypeOf(new Pikaday()) === Pikaday.prototype
);

console.log(
  Reflect.getPrototypeOf(new Pikaday()) === Pikaday.prototype
);

您的代码的一个问题是getElementsByClassName将返回具有此类的节点的NodeList(不是数组)。

这意味着您必须遍历此列表并将处理程序附加到每个元素,

let nodes = document.getElementsByClassName('pika-year-label');
Array.from(nodes) // convert NodeList to an array so we can use forEach
  .forEach(node => {
    // attach a handler on each node
    node.onclick = function (){
      console.log("asfd");
    }
  });

// Side Note: You can also use array spread to convert the node list to an array
// [...nodes].forEach( ... )

或者将处理程序附加到所有元素的公共父级以委托行为。

document.body.onclick = function(e) {
  if (e.target.classList.contains('pika-year-label')) {
    console.log("asfd");
  }
}

最后,如果您只想将此函数添加到现有函数的原型中,一种方法是将其简单地定义为该原型上的方法:

function Pikaday() {}

// define a method on the existing prototype
Pikaday.prototype.showYearPicker = function() {
  console.log('called');
};

let pikaday = new Pikaday();
pikaday.showYearPicker(); // <-- call the function on the prototype

于 2016-12-05T02:30:41.667 回答