Javascript Prototypes,objects,constructor??i am co

2019-01-26 19:42发布

问题:

I have gone through plenty of Stack Overflow question that had description but I seriously found them very confusing. What I want is a simple explanation,please don't refer a link.

I'm totally confused, completely jumbled up between:

  • Prototypes,

  • Objects,

  • Constructor

I have done plenty of research but I found them very complicated.

Any simple explanation??

回答1:

You're in luck. There's a very simple explanation:

Step One: Create an Object

Say you want to circle:

var circle = {};

Step Two: Give it Some Properties

A circle can be drawn, so let's create a property called draw:

circle.draw = function () {
    // drawing logic
};
  1. A property is simply a variable belonging to an object. A variable by itself is not a property.
  2. Properties and variables can hold any kind of data. Functions in JavaScript is data.
  3. When a property holds a function it's called a method.

Hence we have a method called draw belonging to the object circle.

Step Three: Extend an Object

Now I want a ball and a ball is kind of like a circle. So let's extend circle to create a ball:

var ball = Object.create(circle);
  1. Here we took the object circle and used it to create a new object called ball.
  2. The object ball now has all the properties of circle. So we can call ball.draw.
  3. The object circle is the prototype of ball.

Step Four: Give it Some Properties

Every ball has a radius, so let's give ours one:

ball.radius = 5;

Step Five: Create a Constructor

There's a problem here. Every time I want to create a new ball I extend circle and manually define the radius of the ball. Instead I would like a function to create the ball and give it a radius for me. This function is called a constructor:

function createBall(radius) {
    var ball = Object.create(circle);
    ball.radius = radius;
    return ball;
}

var baseball = createBall(5);
var basketball = createBall(10);

baseball.draw();
basketball.draw();

That's pretty much all you need to know about prototypes, objects and constructors.

Of course there's a lot more explanation but it's too much for one StackOverflow answer. I wrote a blog post on it, and I'm not planning to rewrite the same thing here. You should read my blog. It's worth it: http://aaditmshah.github.io/why-prototypal-inheritance-matters


Edit: Sure, I'll explain what happening in that code: http://cssdeck.com/labs/4ksohwya

First, scroll down to the very end:

window.addEventListener(
    'load',
    init(null),
    false);

When the page loads it executes init:

function init(images) {

    canvas= document.getElementById('s');
    ctx= canvas.getContext('2d');
    canvas.width= window.innerWidth;
    canvas.height=window.innerHeight;

    garden= new Garden();
    garden.initialize(canvas.width, canvas.height, 300);

    lerp(0,2000);

    time= new Date().getTime();
    interval = setInterval(_doit, 30);
}

The init function creates an instance of Garden (garden = new Garden();) and executes the initialize method of garden. It also calls the _doit function in intervals of 30 milliseconds.

initialize : function(width, height, size)  {
  this.width= width;
  this.height= height;
  this.grass= [];

  for(var i=0; i<size; i++ ) {
    var g= new Grass();
    g.initialize(
        width,
        height,
        50,      // min grass height 
        height*2/3, // max grass height
        20,     // grass max initial random angle 
        40      // max random angle for animation 
        );
    this.grass.push(g);
  }

  this.stars= [];
  for( i=0; i<this.num_stars; i++ )  {
    this.stars.push( Math.floor( Math.random()*(width-10)+5  ) );
    this.stars.push( Math.floor( Math.random()*(height-10)+5 ) );
  }
},

The initialize method of garden then creates some instances of Grass, calls their initialize methods and stores them in an array.

function _doit()    {

  ctx.fillStyle= gradient;
  ctx.fillRect(0,0,canvas.width,canvas.height);
  var ntime= new Date().getTime();
  var elapsed= ntime-time;
  garden.paint( ctx, elapsed );

  // lerp.
  if ( elapsed>nextLerpTime ) {
    lerpindex= Math.floor((elapsed-nextLerpTime)/nextLerpTime);
    if ( (elapsed-nextLerpTime)%nextLerpTime<lerpTime ) {
      lerp( (elapsed-nextLerpTime)%nextLerpTime, lerpTime );
    }
  }

}

The _doit function calls the paint function of garden, and the paint function of garden calls the paint function of each grass.


So here there are two constructors:

  1. Grass
  2. Garden

Here are the two prototypes:

  1. Grass.prototype
  2. Garden.prototype

Inside the init function we create a single instance of Garden (that's one object):

var garden= new Garden();

Inside the initialize method of garden we create multiple instances of Grass:

var g= new Grass();

That's it.



回答2:

Okay, a whirlwind tour:

Objects

An object is a thing that has properties. Properties have names and values. The names are always strings (although we can write them without quotes most of the time), and the values can be anything JavaScript supports: Numbers, strings, booleans, null, undefined, or references to objects.

So:

var a = {
    propertyName: "property value"
};

a is a variable referring to an object, which has a property named propertyName, whose value is the string "property value".

Prototypes

An object (say, obj) can have another object (say, p) "behind" it, where p lends obj its properties unless obj has its own property with a given name. p is the prototype object of obj. This is easiest to understand with an example:

// Let's create an object `p` with a couple of properties, `x` and `y`
// This syntax is called an "object initializer" (aka "object literal")
var p = {
    x: "x on p",
    y: "y on p"
};

// Now, we'll create a new object, `obj`, using `p` as its prototype
var obj = Object.create(p);

// And that means if we ask `obj` for a property called `x`, since it doesn't
// have its **own** `x`, it asks `p` for it. (And the same with `y`)
console.log(obj.x); // "x on p"
console.log(obj.y); // "y on p"

// But we can give `obj` its *own* `x` instead if we want
obj.x = "x on obj";
console.log(obj.x); // "x on obj"
console.log(obj.y); // "y on p"

// Doing that to `obj` had no effect on `p`
console.log(p.x); // "x on p"
console.log(p.y); // "y on p"

A very, very important aspect of prototypes is that the connection between the objects is live. So if obj doesn't have a y property, every time we ask obj for y it goes and asks p. And so if we change p's value for y, that change shows up if we ask obj for it:

var p = {
    x: "x on p",
    y: "y on p"
};

var obj = Object.create(p);

console.log(obj.y); // "y on p"

p.y = "updated y on p";

console.log(obj.y); // "updated y on p"

This live connection is a vital thing. So again, think of it like this: We ask obj for the property y, and obj says "I don't have my own, so I'll go ask p for it and give you that."

Note: The Object.create function I've been using to create obj is new as ECMAScript5 (the spec update from a couple of years ago). We'll come back to another way to given an object a prototype further down.

The prototype for an object is currently always set when the object is created, and cannot be changed (I couldn't swap in a q instead of p above after creating obj). Above I'm using Object.create to do it (and below we'll talk about constructor functions). Until ECMAScript5 (ES5), there was no standard way to get the prototype of an object. ES5 gives us a way to do it now, called Object.getPrototypeOf, but still doesn't offer a way to change it. The next version, ES6, will take things a bit further.

Functions

Functions are units of code that do things. Functions are also objects, and so they can have properties, although in practice it's relatively rare to use properties on functions (other than call and apply, which we don't need to talk about here).

You can declare a function:

function foo() {
}

...or you can create one with an expression:

// An anonymous -- unnamed -- function assigned to variable `foo`
var foo = function() {
};

// A function named `f` assigned to variable `foo`
var foo = function f() {
};

Declarations and expressions are different. Function declarations are evaluated before any step-by-step code in the same scope is performed. Function expressions are evaluated as they're encountered in the step-by-step code, like all other expressions. (People sometime call this "hoisting" because it means that in effect, even if a function declaration is at the bottom of a scope, it happens as though it had been lifted -- hoisted -- to the top.)

Functions can have arguments:

// `a` and `b` are arguments
function sum(a, b) {
    console.log(a + b);
}

And they can have return values:

function sum(a, b) {
    return a + b;
}
console.log(sum(1, 2)); // "3"

If a function doesn't return something else, the result of calling the function is the value undefined.

Methods

JavaScript doesn't have methods. It only has functions — but that's all it really needs. But if you have a function assigned to an object property, and you call that function as part of an expression retrieving the property from the object, then something happens that makes JavaScript seem to have methods: The this keyword refers to that object within the function call. Again, an example works wonders:

// A blank object
var obj = {};

// Lets put a function on it as a property
obj.foo = function() {
    console.log("this is obj? " + this === obj);
};

// Let's call that function
obj.foo(); // "this is obj? true"

More on my blog:

  • Mythical Methods
  • You must remember this

Constructors

Constructor functions are used with the new keyword, and they're one of the ways you give an object a prototype. When you call a function via new, a new object is created, and assigned a prototype from the function's prototype property:

function Foo() {
}
Foo.prototype.x = "x on Foo.prototype";

var obj = new Foo();
console.log(obj.x); // "x on Foo.prototype"

Every function automatically has a prototype property, even though of course we don't use the vast majority of functions as constructors.

An important thing to note here: The prototype property of a function is just a boring old property. It isn't the prototype of any object until/unless that function is called via the new operator. The new operator uses the prototype property of the function to set the prototype of the new object when you call the function via new, but that's all.

It's worth mentioning that until ES5, constructor functions like the above were the only way you could create an object with a given prototype. But with ES5, we got Object.create, which opened up more patterns for how to use JavaScript. (It was always possible to create your own Object.create, by using a temporary function, and in fact that's exactly what some people did.) Some people don't like using the new keyword and the prototype property, they prefer to use a "builder" pattern where you just call a function and get back an object. JavaScript is so flexible that you can do that.


More to Explore

  • I write about JavaScript on my blog: Nifty Snippets - javascript label

  • The Mozilla Development Network has excellent JavaScript information

  • There is, of course, the specification — it's the best source for the actual nitty-gritty detail, but it's very hard reading :-)



回答3:

I guess I am too late, but here would be my 2 cents:

Prototype:

String.prototype.x = "yahoo"

now every instance of String will have the property x.

So be it (new String()).x or "".x both have the value equal to yahoo

Hence it's like extending a predefined class.


Objects

Everything in JavaScript, except the other primitive types, is an object.

An object is a collection of name-value pairs, nothing more, nothing less.

{"a": 0, "b" : 1}

Even an Array is an object in JS with some additional properties & methods.


Functions & Methods

Here is a function :

function a() { };

Now let's give it the status of a method of an Array:

Array.prototype.a = a;

Constructor:

new String()

gets the implementation of String from : String.constructor

Similarly the code you write in any function goes into this very function.



回答4:

JavaScript is the scripting language used in web applications to make the web pages dynamic. This language allows to handle user actions by handling events on the elements displayed on the page.... Also it is used to modify the content on the web page based on the condition...

The method (or) function is the programming construct used in javascript for specifying the logic. You will put the your required logic in a method and you will invoke it from the web page upon any event...

There are no constructors in javascript...

There will be implicit and user defined objects in javascript... Implicit objects include Date, Array etc...

This is just a basic abstract.. you need to follow either websites (or) books to know much more about javascript