문제

I'm coming at this from the OOP world and trying to wrap my head around "classes" in Javascript. I'd like to be able to create a class with properties but not have to assign values to them right away. Something like the following:

var MyObject = function(id) {
    this.id = id;
    // Create the property so it is present on all instances but don't require it to be assigned to right away.
    this.friendId;
}

MyObject.prototype = {
    constructor: MyObject

    // Etc...
}

Is there a way to do this or am I just not getting how it works in Javascript?

도움이 되었습니까?

해결책

Simply omit the property from the declaration:

function MyObject(id) 
{
    this.id = id;
}

var obj = new MyObject(123);
console.log(obj.friendId); // undefined

Alternatively, explicitly set it to null in the constructor.

다른 팁

This Mozilla Developer Network article is a good read. It compares Class based and Prototype based languages and provides side by side codes samples in Java and in JavaScript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

Quoting from the article.

Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top