JavaScript - 使用对象原型来扩展方法的用法?

ran*_*ath 0 javascript constructor prototype object

我是JavaScript的新手,在使用我的对象的原型时,我尝试调用当前对象来扩展方法,但它无法正常工作.所以我谷歌我的问题,但没有真正得到任何地方,因为它几乎是不可能的短语.但是,我发现了this我认为应该有效的关键字,但没有.这就是我所拥有的:

(function( window, document, undefined ) {
    var myObj = function ( ) { }; // not a noop
    var ua = function() { return navigator.userAgent.toLowerCase(); }
    function noop() { }; // empty noop function

    myObj.prototype = {
        constructor: myObj,
        renderizr: {
            presto: ua().match(/(opera|presto)/i),
            trident: ua().match(/trident/i), // don't parse "msie" as opera uses this sometimes
            webkit: ua().match(/(chrome|safari|webkit)/i),
            gecko: ua().match(/(firefox|gecko)/i), // don't parse "netscape" as a lot of strings use this
            val: '' // keep empty for now
        }
    };

    // renderizr.val extension
    // use this so the user can print the value of
    // the rendering engine instead of using multiple
    // conditional statements.
        if(this.renderizr.presto) { this.renderizr.val = "Presto" }
        else if(this.renderizr.trident) { this.renderizr.val = "Trident") }
        else if(this.renderizr.webkit) { this.renderizr.val = "Webkit") }
        else if(this.renderizr.gecko) { this.renderizr.val = "Gecko") }

    window.myObj = new myObj();
}( window, document ));
Run Code Online (Sandbox Code Playgroud)

这样,您就可以alert(myObj.renderizr.val);而不是单调的条件语句.

我不想进行通用浏览器名称检测,因为您只应测试所需的功能,而不是浏览器.但是,一些渲染引擎有不同的渲染网页的习惯,所以我想在我的脚本中包含引擎检测.(但是,我不建议使用它,就像我说的,我只是想了解javascript以及它是如何工作的,而且它不起作用!).

所以我的问题是,我在这里做错了什么,我该如何解决?为什么this关键字不起作用?

Hal*_*yon 5

您正在使用this不在myObj对象实例中的上下文中.this将是全球范围(即窗口).

此外,您的所有代码都在立即运行,您没有在您的代码中定义任何函数prototype.