使用构造函数添加方法

Using constructor function to add methods

本文关键字:方法 添加 构造函数      更新时间:2023-09-26

创建构造函数的经典方法如下:

var Obj = function(param){
    this.param = param;
    this.method = function(){ console.log(this.param); }
}

但是为什么我不能这样做呢?

Obj.anotherMethod = function(){ //some code }

(I know about Obj.prototype.anotherMethod).

在实际使用中,我不能理解为什么用String.prototype.func代替String.func来定义新方法。是不是因为String是构造函数,不能给它添加方法?

这是两码事。

如果你添加一个方法到Constructor.prototype,它将在Constructor的所有实例上可用。

您也可以为Constructor本身添加方法。但是,实例不会继承它们。

例如,

  • charAt方法是在String.prototype上定义的,所以你可以同时使用"abc".charAt(1)String.prototype.charAt.call("abc", 1)

  • 但是fromCharCode是在String上定义的,所以你可以使用String.fromCharCode(65),但是"abc".fromCharCode是未定义的

您可以通过原型继承来做到这一点。您可以使用Object.create()让对象从其他对象继承,而不是使用构造函数。你可以随时向父对象添加成员,并且这些成员对于以父对象为原型的对象是可用的。

var Base = {a: "a"};
Base.b = "b";
var sub = Object.create(Base); // creates a new object with Base as its prototype
Base.c = "c"; // sub.c will be available because Base is its prototype!
alert(sub.a + sub.b + sub.c); // "abc"
http://jsfiddle.net/kqtm4f8j/

理解原型继承模式的好文章:

http://aaditmshah.github.io/why-prototypal-inheritance-matters/

下面的一小段代码应该会有所帮助。从构造函数开始:

var Obj = function(param){
    this.param = param;
    this.method = function(){ console.log(this.param); }
}

现在创建一个实例:

var inst = new Obj("testParam")
//now use it
console.log(inst.param) // logs: "testparam

现在给Obj添加另一个参数:

Obj.anotherParam = "TestParam2"
console.log(Obj.anotherParam) // <-- Works
console.log(inst.anotherParam) // <-- but this is Undefined on the instance

但是如果你把它添加到原型中:

Obj.prototype.anotherParam = "TestParam2"
console.log(inst.anotherParam) // <-- this now works as expected

结论是,当你将它添加到原型中时,它对所有实例都可用。如果简单地将其添加到构造函数中,则只有构造函数函数具有该参数。在Javascript中有很多其他的方法可以做到这一点,但是理解原型对象是一个很好的开始。