javascript - 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'。我不知道为什么我不能使用原型方法,请给我一些建议。我会很感激的。
解决方案
没有类的基于原型的继承在 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(...) { ... }
}
推荐阅读
- android - Gradle失败评估项目':app'时出现问题
- coq - 如何证明(proj1_sig fa)和(proj1_sig fb)两个对象的等价性,其中a和b是等价的
- python - mac osx上的Python lightblue模块
- matlab - 线性回归(regress)与多项式拟合(polyfit)的差异
- unit-testing - Truffle uint 测试脚本不反映更新的存储变量和奇怪的行为
- android - 计算TextView中可见字符数
- angular - 使用不记名令牌和 net::ERR_CERT_AUTHORITY_INVALID 错误的远程 API 调用
- sql - 如何计算雅典娜(Presto)中2个时间戳之间的差距?
- asp.net - 使用 SelectPDF 导出 JQGrid,链接的 JQGrid 中没有数据
- sql - 需要将这两者之间的差异作为输出