Written in front: note from www.bilibili.com/video/BV1iX… Assault delete

Reactive means reactive

1. Why define defineReactive()?

It’s actually the object.defineProperty () function that doesn’t work \

Look at the get function:

The get function must return a value:Let’s look at the remaining issues with the last note:

We said that the get function must have a return value, so let’s add the return value to it:

Once it’s wrapped as a function, you don’t have to declare one

Now this 7 can be displayed properly. There is no problem.

Now look at the set function:

Here’s what it means:

Did you find anything magical?

You tried to change OBJ.B, but did you end up with 10 or 7?

Is still 7

That means your assignment failed

Why??

Because:

When you access obj. B, you still call get and get the return result. I don’t think I’ve been here.

To solve this problem, we set a variable temp

Results:

Here’s another test:

Results:

Summary:

In order to ensure the real-time performance of set and GET data, we introduce an intermediate variable temp for turnover (important).Copy the code

Next, look at the defineReactive() function

Temporary variables don't look pretty, so we wrap them in functions and use function closures to do the job. DefineReactive () is the outer layer of the nested get() and set()Copy the code
var obj = {}; Function defineReactive(data,key,val){object.defineProperty (data,key,{// Enumerable :true, // Get (){console.log(64x, 64x, 64x, 64x, 64X, 64X, 64X, 64X, 64X, 64X, 64X, 64X); Set (newValue){console.log(' you tried to change obj's A property ',newValue) if(val == newValue){return} val = newValue}})} defineReactive(obj,'a',10) console.log(obj.a) obj.a = 111 obj.a ++ console.log(obj.a)Copy the code

The code doesn’t look good:

This thinking is absolutely absolutely son!!

Conclusion:

Get () and set() in object.defineProperty () is why MVVM in VUE can implement the effect of changing views as soon as data changes. But here we need a transition variable to receive and change and in order to elegantly represent that transition variable, we encapsulate it as a function; This is the defineReactive() function