简体   繁体   English

所有原型的功能-Javascript

[英]Function for all prototypes - Javascript

I'm working on a video player with video.js. 我正在使用video.js开发视频播放器。 On this side I've got elements (volume, fullscreen, play, pause...) which are prototypes . 在这一方面,我有一些元素(音量,全屏,播放,暂停...)是原型 On the other side I've got my functions parse() which is going to be use by all of the canvas prototypes (they come from different elements). 另一方面,我有我的函数parse() ,它将被所有画布原型使用(它们来自不同的元素)。

parse Function : 解析功能:

vjs.parseHex = function(c) {
    if(c.charAt(0) == "#") {
        return c.substring(1,7);
    } else if(c.substr(0,2) == "0x") {
        return c.substring(2,8);
    } else {
        return c;
    }
},

vjs.parseRed = function(c) {
    return parseInt((this.parseHex(c)).substring(0,2),16);
},

vjs.parseGreen = function(c) {
    return parseInt((this.parseHex(c)).substring(2,4),16);
},

vjs.parseBlue = function(c) {
    return parseInt((this.parseHex(c)).substring(4,6),16);
}

An exemple of my canvas prototype : 我的画布原型的一个例子:

js.VolumeBar.prototype.drawSound = function(){
  .
  .
  .
}

I want that my parse functions are accessible by all of the different prototypes. 我希望所有不同的原型都可以访问我的解析函数。 Is that possible ? 那可能吗 ? If yes, how can I do that? 如果是,我该怎么做?

Thank you for helping me, Léa. 谢谢您对我的帮助,莉亚。

It seems that vjs is a sort of Util namespace that contains a few functions that should be used in different places. 似乎vjs是一种Util命名空间,其中包含一些应在不同位置使用的函数。 As long as that is public it can be used anywhere: 只要是公开的,它就可以在任何地方使用:

vjs = {};
vjs.parseHex = function(c) { /*...*/ }
vjs.parseRed = function(c) { /*...*/ }


js.VolumeBar.prototype.drawSound = function(){
  vjs.parseRed(stuff);
}

Keep in mind that if you pass vjs.parseRed as a callback, it will be called with a different object as this than what you expect. 请记住,如果你通过vjs.parseRed作为回调,将有不同的对象叫this不是你所期望的。 You could rewrite it to either 您可以将其重写为

  • replace this with vjs : vjs替换this

    vjs.parseRed = function(c) { return parseInt((vjs.parseHex(c)).substring(0,2),16); }

  • bind the functions when you pass them as parameters: 当您将函数作为参数传递时,请绑定它们:

    doAsync(vjs.parseRed.bind(vjs));

  • or just bind them when you define them: 或在定义它们时将它们绑定:

    vjs.parseRed = function(c) { /*...*/ }.bind(vjs);

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

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