Object Oriented questions in Javascript

前端 未结 7 1780
轮回少年
轮回少年 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:22

    Your example #1 shows the usage of the prototype property. This property is available to all javascript objects you create and allows you to add properties or functions to the object declaration, so you had a object with 2 properties and later on you added 4 functions (getters and setters).

    You should see the prototype property as the way to modify your object specification at runtime, say you have an object called name:

    var Name = {
      First: "",
      Last: ""
    };
    

    You can use the prototype to add a function getFullName() later on by simply:

    Name.prototype.getFullName = function() { return this.First + " " + this.Last; }
    

    In the example 2 you inline the declaration of these getters and setters in the object declaration so in the end they are the same. Finally on the 3rd example you use the JavaScript object notation you should see JSON.

    About your question 2 you can just declare your object as:

    var User = {
      name: "",
      age: 0
    };
    

    this will give you the same object without getters and setters.

提交回复
热议问题