简体   繁体   中英

Javascript Methods/Objects

I think I finally wrapped my head around understanding how methods, constructor functions, and objects work. Could someone please review my code, and let me know if I using the correct names and syntax? Thanks a ton!

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

Methods of Javascript classes should be defined as prototype:

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

Everything else seems fine to me though.

Use prototype functions. Else your inner functions get copied with every instance.

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

There are many other patterns which for example prevent the pollution of the global scope or allow a more class like approach. (Object literal, Module Pattern, Self-Executing Anonymous Functions)

The same example with the module pattern:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM