簡體   English   中英

Javascript方法/對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM