0

I'm reading a beginner's guide on machine learning from scratch with JavaScript.

About a 1/4 way down the page is the section titled "THE CODE". Right under that section heading is the code in question.

var Node = function(object) {  
    for (var key in object)
    {
        this[key] = object[key];
    }
};

I realize this could be a very basic constructor function but I've never seen this pattern before.

Is there any links or guides about this pattern design or type of constructor. I'd like to learn as much as possible as I can about it.

11
  • 4
    Looks like what you could call a "copy constructor". Commented Jun 23, 2017 at 2:41
  • Copying one object's properties into a new object instead of typing this.prop=1 (etc) manually. Someone from C++ background is having fun with EcmaScript 6 for-in loop. Commented Jun 23, 2017 at 2:45
  • @InfiniteStack for-in is defined in ES1... Commented Jun 23, 2017 at 2:49
  • 1
    @qarthandso The constructor should know what properties to expect, and only explicitly assign those. Commented Jun 23, 2017 at 5:42
  • 1
    @qarthandso The guide explicitly states "It just expects an object with the properties "type", "area", and "rooms"." So the code should reflect that and read this.type = object.type; this.area = object.area; this.rooms = object.rooms; instead of that loop. Commented Jun 23, 2017 at 14:56

1 Answer 1

1

There's not much to learn about or understand. It's simply constructing a new object and copying the properties from some other object into it.

In modern JS, you could also write

function Node(object) {
  Object.assign(this, object);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's a constructor when it's supposed to be called with new. We cannot really judge that from the code, the only hint we have is the capitalisation of the function name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.