Problem: Now we have three components: component A, component B, and component C, all of which have the same properties, data, methods, and even the same life cycle processing, such as printing certain logs in the life cycle Attached.

To solve code reuse between components, applets provide us with behaviors. Consider the official documentation for definitions of behaviors:





Now let’s create a new component called Test and a Behaviors we call test-BEH.








In test-beh, we define a content of type String, set its default value to 22, and export it.





As shown in the figure above, we introduce the behaviors in the component’s JS code. Here is why the behaviors are an array. Each component can reference multiple behaviors, such as behaviors: [testBeh, a, B, c……] .





Then we bind the content variable in the component’s WXML and reference the component on the page.





As shown above, we print out that the value of content is 22.


As we mentioned earlier, a component can reference multiple behaviors, so there is the problem of overwriting fields with the same name.

So let’s take a look at the official field coverage and combination rules:

The component and its referenced behaviors can contain fields of the same name. These fields are treated as follows:

1. If there is an attribute or method with the same name, the attribute or method of the component will override the attribute or method in the behavior. If multiple behaviors are referenced, the attribute or method in the lower behavior in the definition section will override the attribute or method in the earlier behavior.

2. If there is a data field with the same name, if the data is of object type, object merge will be carried out; if the data is of non-object type, mutual overwrite will be carried out;

3. Lifecycle functions do not overwrite each other, but are called one by one at the corresponding trigger time. If the same behavior is referenced multiple times by a component, its defined lifecycle function is executed only once.