Object Oriented questions in Javascript

前端 未结 7 1777
轮回少年
轮回少年 2020-12-04 08:46

I\'ve been using javascript for a while, but have never learned the language past the basics. I am reading John Resig\'s \"Pro Javascript Techniques\" - I\'m coming up with

7条回答
  •  自闭症患者
    2020-12-04 09:40

    Question #1

    prototype has the benefit of monkey patching. As the first example shows, the function are added after-the-fact. You can continue this to add or replace any methods you need (though, with fair warning).

    Defining objects like #2 is more along the lines of classic OOP. But, then again, monkey patching isn't allowed in all OOP languages.

    Question #2

    In your 3rd function, you don't even need the get and set functions -- name and age are public properties (the potential downside to {}).

    var User = {
      name: "",
      age: 0
    };
    
    User.name = 'Bob';
    User.age = 44;
    
    console.log("User: " + User.name + ", Age: " + User.age);
    

    When you create an object using {} (an object literal), {} is the constructor (varying on browser). But, essentially, no you can't use a constructor in this format.

提交回复
热议问题