Javascript中的原型继承

时间:2013-08-16 10:38:52

标签: javascript inheritance prototype

如何在Javascript中将值传递给超类构造函数。

在以下代码段中

(function wrapper() {
var id = 0;

window.TestClass = TestClass;

function TestClass() {
    id++;
    this.name = 'name_' + id;
    function privateFunc() {
        console.log(name);
    }
    function publicFunc() {
        privateFunc();
    }

    this.publicFunc = publicFunc;
}

function TestString() {
    this.getName = function() {
        console.log("***" + this.name + "****************");
    }
}

TestClass.prototype = new TestString(); 
})();

如何将值传递给TestString构造函数?目前,超类方法使用'this'关键字来使用值。有没有办法直接将值传递给超类构造函数。另外,我想看一个扩展String的简单示例。这会揭开很多东西的神秘面纱。

1 个答案:

答案 0 :(得分:2)

您可以在TestClass()的构造函数中使用以下代码。

TestString.apply(this, arguments);

这将使用新对象作为其上下文调用构造函数。

但请注意,使用[[Prototype]]建立TestClass.prototype = new TestString();链已经调用了一次构造函数。

jsFiddle

  

我想看一个扩展String的简单示例。

您可以扩充其prototype属性。

String.prototype.endsWidth = function(str) {
    return this.slice(-str.length) === str;
};