需要添加自定义类型并在我的表单中使用原型 属性
Need to add a custom type and use a prototype property within my form
我正在尝试创建一个自定义类型,然后在我创建的虚拟表单中使用其原型 属性 向自定义类型添加一个方法。我正在努力思考如何创建一个自定义类型,该类型实际上会创建一个 "new subscriber." 我在弄清楚如何执行此操作时遇到了问题。我对 JavaScript 还是很陌生,这种语法超出了我的范围。 MDN 的文档让我感到困惑,所以我决定寻求帮助。我创建了一个 JSfiddle,非常感谢社区提供的所有帮助。
www.jsfiddle.net/cbadrew00/ex67bbsj/11/
谢谢你,
您可以通过创建将 "construct" 新对象属性的函数来创建自定义类型,如下所示:
function User(name, email) {
this.name = name;
this.email = email;
}
User
中的this
引用是新对象实例,使用new
创建。
然后你构造对象使用:
var user = new User("John", "john@somwhere.com");
您可以使用构造函数并尝试创建变量的私有版本:
var Subscriber = function (name, email) {
var _name = name,
_email = email,
self = this; // This is used so we can get the name and email variables
this.name = _name;
this.email = _email;
//To add functions, use this.FunctionName = function () {
this.validate = function () {
if (_name == '') {
alert('Enter a name');
return false; // Saying that it is invalid
}
if (_email == '') {
alert('Enter an email');
return false; // Saying that it is invalid
}
return true;
};
this.send = function () {
if (self.validate()) { //Validates it
alert('You are now a subscriber!');
}
};
};
然后像这样使用它:
var subscriber = new Subscriber('Phil', 'phil@philscompany.com');
subscriber.send();
Fiddle
这将添加一个类型 Subscriber
。您可以使用 this.functionName
. 添加函数
我正在尝试创建一个自定义类型,然后在我创建的虚拟表单中使用其原型 属性 向自定义类型添加一个方法。我正在努力思考如何创建一个自定义类型,该类型实际上会创建一个 "new subscriber." 我在弄清楚如何执行此操作时遇到了问题。我对 JavaScript 还是很陌生,这种语法超出了我的范围。 MDN 的文档让我感到困惑,所以我决定寻求帮助。我创建了一个 JSfiddle,非常感谢社区提供的所有帮助。
www.jsfiddle.net/cbadrew00/ex67bbsj/11/
谢谢你,
您可以通过创建将 "construct" 新对象属性的函数来创建自定义类型,如下所示:
function User(name, email) {
this.name = name;
this.email = email;
}
User
中的this
引用是新对象实例,使用new
创建。
然后你构造对象使用:
var user = new User("John", "john@somwhere.com");
您可以使用构造函数并尝试创建变量的私有版本:
var Subscriber = function (name, email) {
var _name = name,
_email = email,
self = this; // This is used so we can get the name and email variables
this.name = _name;
this.email = _email;
//To add functions, use this.FunctionName = function () {
this.validate = function () {
if (_name == '') {
alert('Enter a name');
return false; // Saying that it is invalid
}
if (_email == '') {
alert('Enter an email');
return false; // Saying that it is invalid
}
return true;
};
this.send = function () {
if (self.validate()) { //Validates it
alert('You are now a subscriber!');
}
};
};
然后像这样使用它:
var subscriber = new Subscriber('Phil', 'phil@philscompany.com');
subscriber.send();
Fiddle
这将添加一个类型
Subscriber
。您可以使用 this.functionName
. 添加函数