In society, when evaluating a person's ability and value, there are often two different criteria: one is "based on relationships" and the other is "based on ability". Both standards are embodied in different cultures, industries, and personal values, each with its own supporters and detractors.
Within programming languages, there are two kinds of standards that organize code in different ways, linking data structures to functions. This article will briefly discuss the application and principle of action of these two common standards.
class model
In the Javascript language, the class keyword is provided, which we can use to define classes. Importantly, classes are extensible, and when methods are called on an instance, they look up method definitions in the order of the prototype chain. For example:
class Animal {
move() { return 'move' }
}
class Monkey extends Animal {
jump() { return 'jump' }
}
class Human extends Monkey {
write() { return 'write' }
}
extends
Keywords can help us define a new class that extends from other classes. We can get the prototype chain like this:
let me = new Human()
let proto = me.__proto__
let r = []
while (proto !== null) {
r.push(proto.constructor.name)
proto = proto.__proto__
}
We'll get r
like this: ['Human', 'Monkey', 'Animal', 'Object']
. When we call a method, the success of the method call depends on whether there is a corresponding definition on the prototype chain. For example, if you call me.move()
, it has a definition in the Animal class, and the call succeeds.
This is the class model, which I like to call as a "relational" model, which can be called as long as it is defined in the class of the instance itself, or in the parent class, grandparent class, and so on.
Competency-based model
Compared to the relationship-based model, the competency-based model is much simpler. As long as an instance satisfies a certain trait, the corresponding method can act on the instance regardless of the relationship of the instance.
let me = {
moveable: true,
freezable: false
}
function move(x) { return x.moveable ? 'move' : undefined }
function freeze(x) { return x.freezable ? 'freeze' : undefined }
In this model, data and methods are independent of each other. The advantage is that it is concise and straightforward, but the disadvantage is obvious, because of the independence of the method and the data, it is difficult to override the method definition.
summary
After introducing the two ways of connecting data structures and methods, we can think that when it is necessary to implement methods with different functions of the same name according to the class of the data, it is recommended to use the relational class model. When the method is usually relatively fixed, and the data is changeable, and the same method works on different data, the Competency-based model can be used.
Top comments (0)