M
M
ML2017-01-07 15:21:43
JavaScript
ML, 2017-01-07 15:21:43

How to distinguish between methods and properties in oop?

Here is an example class

var FirstClass = function() {
this.name //как я понял это свойство
};
FirstClass.prototype.dataName = {...}; //это метод
var first_class = new FirstClass();

When should you use methods and when should you use properties?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
EVG, 2017-01-08
@staffID

Method - a
function that represents the value of a property
, which can be called as a subroutine. ( es5.javascript.ru/x4.html#x4.3.24 )
... and therefore...

function isFunction(obj){
  return (typeof(obj)) === "function";
}

Specifically, this.name is a property of the object created by calling the constructor of the FirstClass class. FirstClass.prototype.dataName is a property of the prototype object of the FirstClass class. Whether they are methods or not, you can find out by calling the isFunction function described above.
The fact is that the ECMA Script 5 specification ( es5.javascript.ru ) does not contain the concept of classes as such. But there are object constructors (the new operator) to which you can pass almost any function that will be used as a constructor function. Functions have a prototype property, which is used to pass "parent" behavior and properties to children. Such inheritance is called prototypal.
When implementing inheritance, the mechanism is as follows. The prototype property essentially stores the object's template., which will be obtained when the object is constructed by calling the new operator. There is one thing, however, the properties of an object from the prototype of the parent class are not written to the properties of the created object (more precisely, the entire reference to the object referenced by prototype), but to its special property __proto__ (that is, they are added to the prototype chain).
Check out this trick.
// Объявляем первый класс
Class1 = function(name){this.name = name}
Class1.prototype.family = "Super Class"

// Объявляем второй класс
Class2 = function(name){this.name = name;this.family = "Class";}
// Именно так правильнее указывать родительский класс
Class2.prototype = Object.create(Class1.prototype)

o = new Class2("MyName");

console.log(o.name);
console.log(o.family);

// Объект отказался от своего имени и фамилии
delete o.name;
delete o.family;

// от имени и фамилии можно отказаться
console.log(o.name);
// но не от родовой метки :)
console.log(o.family);

The fact is that the family property was removed from the object, but it is in the object to which the o.__proto__ property refers, following the prototype chain, the interpreter finds the family property and returns its value

V
Vladimir Borutkin, 2017-01-07
@Atanvar

properties - some class data (name, age, gender, etc.)
methods - some class actions (Go, call, bark, jump, etc.)

D
dmz9, 2017-01-07
@dmz9

It's about encapsulation.
An object can have public (public) and private (private) properties/methods.
in JS this is less pronounced (but it can be mimicked), but other languages ​​have such modifiers.
the difference is that public properties are available to any other object/method that interacts with the original object. similarly, public methods are needed for open interaction. private ones are only needed for themselves, just like some methods are only needed inside the object and not outside.
whether to use properties for objects? may not be used at all. use read-write values ​​instead. however, this complicates the code.
if you write code for the public - then do these methods.
if you write code in your small app, it makes little sense.
example of private and public properties. in fact, another object is given "to the outside world", but this does not mean that it has ceased to "work".

var TheConstructor = function(params) {
    var
        happinessCap = 100,
        desireCap = 100,
        ageFactor = (function(age) {
            return 33 / age;
        })(params.age),
        maxAge=45,
        minAge=18,
        woman = {
            _age: params.age,
            _happiness: 42,
            _desire: 0,
            bitchCoeff: params.bitchCoeff
        };
    woman.dance = function() {
        woman._happiness += woman._age / woman.bitchCoeff;
        if (woman._happiness >= happinessCap) {
            woman._happiness = happinessCap;
        }
    }
    woman.drinkAlcohol = function() {
    	if(woman._age<minAge){
    		throw new AgeRestriction(woman._age);
    	}
    	if(woman._age>maxAge){
    		return;
    	}
        woman._desire += woman._age * ageFactor / woman.bitchCoeff;
        if (woman._desire >= desireCap) {
            woman._desire = desireCap;
        }
    }
    woman.isAccessible = function() {
        return (woman._happiness == happinessCap && woman._desire == desireCap);
    }
    return {
        dance: woman.dance,
        drink: woman.drinkAlcohol,
        isAccessible: woman.isAccessible,
        own:function(){
        	return (woman.bitchCoeff<1)?woman:{};
        }
    }
}
function seduce(woman){
  var maxAttempts = 5;
  for(var i = 1;i<=maxAttempts;i++){
    woman.drink();
    woman.dance();
    if(woman.isAccessible()){
      console.log(woman.name + " has been seducted after "+i+" attempts!");
      console.info(woman.own());
      return true;
    }
  }
  console.error(woman.name + " is a frigid bitch!");
  return false;
}
var cheerLeader = new TheConstructor({age:20,bitchCoeff:0.25})
cheerLeader.name = "Masha";
seduce(cheerLeader);
var businessWoman = new TheConstructor({age:33,bitchCoeff:2.5})
businessWoman.name="Olga Victorovna";
seduce(businessWoman);
var schoolTeacher = new TheConstructor({age:27,bitchCoeff:1.1})
schoolTeacher.name="Valentina";
seduce(schoolTeacher);

------------
properties begin with a small letter, are nouns, if more than 1 word is written camel-case.
private properties start with an underscore (it's easier to distinguish this way). for example
, if you use jikveri - there is an unspoken agreement (or maybe fixed somewhere) that the property or variable containing the jikveri object starts with $, for example this.$container = $('.container');
-------------
methods - also start with a small letter, are verbs. if more than 1 word is written kemel-case, the first word is still a verb, the rest can be nouns. e.g. this.getStorageData('orders'), type, get data (orders) from storage.
There are also methods - constructors. these are object methods that return not just a result, but a whole new object, into which various properties are crammed. constructor methods usually start with a capital letter.
For example
-------------

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question