Javascript方法/对象

时间:2014-02-01 23:10:15

标签: javascript

我想我终于理解了方法,构造函数和对象是如何工作的。有人可以查看我的代码,如果我使用正确的名称和语法,请告诉我?万分感谢!

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());  

2 个答案:

答案 0 :(得分:1)

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");

但其他一切似乎都很好。

答案 1 :(得分:0)

使用原型功能。否则,每个实例都会复制你的内部函数。

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());