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

JavaScript-使用对象原型来扩展方法的使用?,javascript,object,constructor,prototype,Javascript,Object,Constructor,Prototype,我对JavaScript非常陌生,在使用对象的原型时,我尝试调用当前对象来扩展方法,但它不起作用。所以我用谷歌搜索了我的问题,但没有真正解决,因为这几乎是不可能的。然而,我找到了这个关键字,我认为它应该有效,但没有。以下是我所拥有的: (function( window, document, undefined ) { var myObj = function ( ) { }; // not a noop var ua = function() { return navigato

我对JavaScript非常陌生,在使用对象的原型时,我尝试调用当前对象来扩展方法,但它不起作用。所以我用谷歌搜索了我的问题,但没有真正解决,因为这几乎是不可能的。然而,我找到了
这个
关键字,我认为它应该有效,但没有。以下是我所拥有的:

(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 ));
这样,您可以执行
警报(myObj.renderizr.val)而不是执行单调的条件语句

我不想做一般的浏览器名称检测,因为你只需要测试你需要的功能,而不是浏览器。但是,一些呈现引擎在呈现网页时有不同的习惯,因此我确实希望在脚本中包含引擎检测。(然而,我不建议使用这个,就像我说的,我只是想了解javascript及其工作原理,但它不工作!)


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

您正在使用
this
的上下文中,您不在
myObj
对象的实例中<代码>此
将是全局范围(即窗口)


另外,您的所有代码都会立即运行,您没有在
原型中定义任何函数

我相信您希望在构造函数中进行这些检查:

var myObj = function () {
    // 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" }
};

另外,在
语句中还有一些额外的
,这会导致语法错误。在这里检查一个工作版本:。

好的,那么我该怎么做呢?我不能将条件语句放在变量范围内。在范围之外,我不能使用
。如果我使用
myObj
myObj
尚未定义。关于如何正确执行此操作,同时保持在立即调用函数表达式的内部,有什么想法吗?我可以将
原型设置为函数而不是子对象吗?比如:
myObj.prototype=function(){……if语句……方法……}
?或者原型必须是对象吗?@randmath:不,不需要,但函数肯定是个坏主意。为什么要这样做?因为函数可以有条件语句,但对象不能,因为它需要另一个变量及其值。还是我错了?有没有我不知道的方法可以做到这一点?@randmath看起来你真的在寻找一个构造函数。查看我的答案。阅读您可以使用
myObj.prototype.renderizr