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

时间:2013-02-12 23:36:50

标签: javascript object constructor prototype

我是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 ));

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

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

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

2 个答案:

答案 0 :(得分:5)

您在不在this对象实例中的上下文中使用myObjthis将成为全球范围(即窗口)。

此外,您的所有代码都在立即运行,您没有在prototype中定义任何功能。

答案 1 :(得分:2)

我相信你想在构造函数中进行这些检查:

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" }
};

此外,您的)语句中还有一些额外的else if,导致语法错误。在此处查看工作版本:http://jsfiddle.net/SnKSB/

相关问题