Javascript - 如何定义构造函数 [英] Javascript - How to define a Constructor
本文介绍了Javascript - 如何定义构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的对象:
Object1.prototype = {
isInit: false,
Get : function (){}
}
现在我想添加一个带有一个参数的构造函数。我该怎么办?
Now I'd like to add a constructor which takes one parameter. How can I do it?
推荐答案
班级声明
var User = function(name, age) { // constructor
}
User.prototype = {}
实例变量(成员)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {}
静态变量
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
staticVar: 15,
anotherStaticVar: 'text'
}
这里我定义了两个静态变量。每个用户实例都可以访问这两个变量。请注意,我们可以使用值初始化它;
Here I defined two static variables. Each User instance has access to these two variables. Note, that we can initialize it with value;
实例函数(方法)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
getName: function() {
return this.name;
},
setName: function(name) {
this.name = name;
}
}
用法示例:
var user = new User('Mike', 29);
user.setName('John');
alert(user.getName()); //should be 'John'
静态函数
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.create = function(name, age) {
return new User(name, age);
}
User.prototype = {}
这篇关于Javascript - 如何定义构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文