[英]right way to make class function in javascript
I have the below code: 我有以下代码:
function Class () {
this.method = function () {
alert('method');
};
}
new Class().method();
And it works fine, but as I understand, for each new object will be created the function. 它工作正常,但是据我了解,将为每个新对象创建函数。 Is there right way to do this?
有正确的方法吗?
Place initialization of instance varibales into the Class function, and shared methods and variables in prototype property: 将实例变量的初始化放到Class函数中,并将共享方法和变量放到prototype属性中:
function Class (var1, var2) {
this.var1 = var1;
this.var2 = var2;
}
Class.prototype.method = function () {
alert(this.var1 + ' ' + this.var2);
};
new Class('var1', 'var2').method();
My approach is almost identical to Speransky's, but I re-declare the prototype object instead of adding methods directly to it. 我的方法几乎与Speransky的方法相同,但是我重新声明了原型对象,而不是直接向其中添加方法。
// Declare the Constructor function.
function MyClass (name, age) {
// Assign any member properties here.
this._name = name;
this.age = age;
}
// Redefine the prototype object to add methods.
MyClass.prototype = {
// Re-point the Constructor function as it will be overwritten.
constructor: MyClass,
// Custom method which all instances of `MyClass` will inherit.
sayHello: function () {
return "My name is " + this._name + ", how do you do?";
}
};
Usage: 用法:
var foo = new MyClass("Dave", 22);
foo.sayHello(); // "My name is Dave, how do you do?"
foo.age; // 22
If you wanted to point the MyClass
prototype at another object (to setup a simple inheritance model) then you could make use of a mixin, similar to Underscore's extend
method: 如果您想将
MyClass
原型指向另一个对象(以设置一个简单的继承模型),则可以使用mixin,类似于Underscore的extend
方法:
function BaseClass(name) {
this._name = name;
}
BaseClass.prototype = {
constructor: BaseClass,
sayHello: function () {
return "My name is " + this._name + ", how do you do?";
}
}
class MyClass (name, age) {
// Call the BaseClass constructor function in the context of `this`
BaseClass.call(this, name);
this.age = age;
}
// Mixin the BaseClass's protptype into the MyClass prototype and delcare
// the new methods.
_.extend(MyClass.Prototype, BaseClass.prototype, {
constructor: MyClass,
getAge: function () {
return this.age;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.