JavaScript:继承和常量声明 [英] JavaScript: Inheritance and Constant declaration

查看:42
本文介绍了JavaScript:继承和常量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助,我有这堂课

var jMath = {

    pi2: Math.PI,

    foo: function() {
        return this.pi2;
    }
}

我想使pi2不变,我想让jMath从Math对象继承.我该怎么办?

I want to make the pi2 constant and i want jMath to inherit from Math object. How do I do that?

推荐答案

哦,好笑的东西,从头开始,这是正确的版本:

Oh amusing, scratch all that, this is the correct version:

function JMath() {
   this.foo = function() {
        return this.PI;
    }
}

JMath.prototype = Math;

var jMath = new JMath();
alert(jMath.foo());

(与此处的其他答案匹配)

(which matches what the other answer is here)

(我最初尝试使用"JMath.prototype = new Math()"设置原型,这是我在其他地方看到的方式,但是上面的方法有效)

(I originally tried to set the prototype using "JMath.prototype = new Math()" which is how I've seen it other places, but the above works)

这里是单例完成的一种方法

Here's one way to do it as a singleton

//  Execute an inline anon function to keep
//  symbols out of global scope
var jMath = (function()
{
    //  Define the JMath "class"
    function JMath() {
        this.foo = function() {
            return this.PI;
        }
    }

    JMath.prototype = Math;

    // return singleton
    return new JMath();
})();

//  test it
alert( jMath.PI );

//  prove that JMath no longer exists
alert( JMath );

这篇关于JavaScript:继承和常量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆