How to properly encode the javascript property and method using the 'prototype' function?

I am trying to learn how to create and use javascript properties and methods using javascript prototypes, and I am a bit difficult.

In the following code, I am trying to create a simple object called "radius" that has a radius of 4 and has a "getCircumference" method that creates a circle using the value of the radius of the object.

function radius()
{
    this = 4;
}

function getCircumference()
{
    var pi = 3.141592;
    var circumference = this.value * 2 * pi;
    document.write(circumference);
}

radius.prototype.circumference = getCircumference;
radius.circumference();

If someone can show me how to make this code work, and even better, how to make this code valid for input of any radius and return a circle every time a new method is called. thank!

+2
source share
3 answers

, , .

this. this.value = 4 pst suggestion ( (new radius()).curcumference()), , .

, , , . :

// traditionally, class name are TitleCased
function Circle(radius) {
    this.radius = radius;
}

Circle.prototype = {
    circumference: function() {
        return this.radius * 2 * Math.PI;
    }
};

var circle = new Circle(4);
document.write(circle.circumference());
+4

: (new radius).circumference() - .prototype "" [[prototype]] "( hint:-) , new.

, : new radius(42).circumference().

. http://jibbering.com/faq/notes/closures/.

+2

:

Function.prototype. Function.prototype Function.

- , prototype / . , , , , .

any JavaScript, ( object ).

:

function example(some, params)
{
  var foo = some;
  this.bar = params;
  //more code...
}

:

window.example('fizz', 'buzz');

, foo , 'fizz' , window.bar 'buzz'.

,

var temp = new example('fizz', 'buzz');

, foo - , 'fizz' , temp.bar 'buzz'.


:

example.prototype.baz = 'w00t';

example baz 'w00t'.

"":

example.prototype.doSomething = function(){ /* do something code */... };

example doSomething, .


, ?

prototype, :

example.prototype.baz = 'new w00t';

However, if you override the instance property, only that instance will be updated :

temp.baz = 'not w00t';

Your example:

You need an object circlewith a radius:

function circle(r)
{
  //probably should do some value checking stuff here
  this.radius = r;
}

Each object circlehas a circle:

circle.prototype.getCircumference()
{
  return Math.PI * 2 * this.radius;
}

Now, if you create a new circle, you can get a circle:

var c = new circle(5);
console.log(c.getCircumference());

Quick note:

defining a function on a prototype allows all instances to share a link to the same function.

If you create a function for each instance:

function temp()
{
  this.func = function(){...};
}

Most likely, you will have worse performance than the ability to share a prototype function:

function temp(){}

temp.func = function(){...};
+2
source

Source: https://habr.com/ru/post/1785359/


All Articles