[英]Javascript Methods/Objects
我想我终于将头绪集中在理解方法,构造函数和对象如何工作上。 有人可以查看我的代码,并让我知道我是否使用正确的名称和语法? 万分感谢!
function objectConstructor (arg1, arg2) {
this.property1 = arg1;
this.property2 = arg2;
this.methodName = functionName;
}
function functionName() {
console.log(this.property1 + ' ' + this.property2);
}
var object1 = new objectConstructor('value1','value2');
console.log(object1.property1);
console.log(object1.methodName());
Javascript类的方法应定义为原型:
var CustomObject = function (arg1, arg2) {
this.property1 = arg1;
this.property2 = arg2;
};
CustomObject.prototype.functionName = function() {
console.log(this.property1 + ' ' + this.property2);
};
var object1 = new CustomObject("value1","value2");
不过,其他一切对我来说似乎都很好。
使用原型函数。 否则,您的内部函数将与每个实例一起复制。
function Person(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function()
{
return this.firstName+' '+this.lastName;
}
var person1 = new Person('foo', 'bar');
console.log(person1.getFullName());
还有许多其他模式,例如可以防止对全球范围的污染或允许使用更类似类的方法。 (对象文字,模块模式,自执行匿名函数)
与模块模式相同的示例:
var Person = (function()
{
var Person = function(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function()
{
return this.firstName+' '+this.lastName;
}
return Person;
})();
var person1 = new Person('foo', 'bar');
console.log(person1.getFullName());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.