首页 > 解决方案 > webview js界面不能使用原型

问题描述

我使用 webview 注入一个对象,就像这样:

public class mediaplayer {

    @JavascriptInterface
    @SuppressWarnings("unused")
    public void testInterface(int num) {
        Log.d("mediaplayer","testInterface2...." + num);
    }

}
 public mediaplayer _mediaplayer = new mediaplayer();
 WebView.addJavascriptInterface(_mediaplayer, "IPTVPlayer");

我想在网页中使用它,就像这样:

function MediaPlayer2()
{

    return IPTVPlayer;
}
MediaPlayer2.prototype.setPlayerParams = function (channel) {

    console.log('MediaPlayer2.prototype.setPlayerParams2................');

};
 var mp2 = new MediaPlayer2(); 
 mp2.setPlayerParams("this is test");

当我运行它时,它会出现错误:

TypeError: Object [object Object] 没有方法'setPlayerParams'


我必须像那样使用 webview 方法,所以必须返回'IPTVPlayer'。我不知道为什么我不能使用原型方法,请给我一些建议。我会很感激的。

标签: javascriptwebviewchromiumv8

解决方案


没有类的基于原型的继承在 JavaScript 中可能非常棘手。您需要做的主要有两件事:

// 1. Correctly set up the constructors to call the super constructor
function MediaPlayer2() {
  // Call the "super" constructor with the new instance (this).
  IPTVPlayer.call(this)
}
// 2. Correctly set up the lookup chain via the prototype
MediaPlayer2.prototype = Object.create(IPTVPlayer.prototype);
MediaPlayer2.prototype.constructor = MediaPlayer2;

// Now you can start adding methods.
MediaPlayer2.prototype.setPlayerParams = ...

我建议继续阅读更多背景工作,并开始使用更明确的 ES6 类:

class MediaPlayer2 extends IPTVPlayer {
  constructor() { super(); ... }
  setPlayerParams(...) { ... }
}

推荐阅读