Thursday, March 27, 2014

JavaScript Methods and Custom Constructors

  • Like a function but used specifically with objects
  • Defined like a function but you add the name after the object
    • bob.setAge = function (newAge)
  • Functions require parameters while methods do not
  • "this" can refer to a specific object without having to write it in the method
    • var setAge = function (newAge) {
        this.age = newAge;
      };
  • Custom constructors work like this
    • function Person(name,age) {
        this.name = name;
        this.age = age;
      }
  • and can be called like this
    • var bob = new Person("Bob Smith", 30);
  • You can also have it so that there will be a value for all objects when making a custom constructor
    • function Person(name,age) {
        this.name = name;
        this.age = age;
        this.species = "Homo Sapiens";
      }
    • There is no parameter for species so Person will always be Homo Sapien
  •  They can also come with methods
    • function Rectangle(height, width) {
        this.height = height;
        this.width = width;
        this.calcArea = function() {
            return this.height * this.width;
        };
        this.calcPerimeter = function() {
            return this.height * 2 + this.width * 2
        }
      }

1 comment:

  1. Fantastic notes! As I've mentioned, I'm really learning JavaScript for the first time myself this year along with you. Looking at your notes it dawned on me why Codeacademy made the choice to use:

    var myFunction = function(...

    instead of:

    function myFunction(...

    They were setting the stage to make JavaScript methods seem natural.

    JavaScript is a fascinating beast. It is what is called a prototype-based language (see http://en.wikipedia.org/wiki/Prototype-based_programming). It doesn't have classes, but instead allows inheritance from instances.

    Again, excellent notes!

    ReplyDelete