Home Web Front-end JS Tutorial Let's talk about the thoughts about getters and setters caused by Vue.js

Let's talk about the thoughts about getters and setters caused by Vue.js

Jan 03, 2017 pm 05:01 PM

Cause

When I printed out the attributes in the data object under the Vue instance, I found an interesting thing:

Each of its attributes There are two corresponding get and set methods. I thought this was unnecessary, so I went online to check the implementation principle of Vue two-way binding, only to find that it is completely different from the implementation principle of Angular.js two-way binding. Angular It uses data dirty detection. When the Model changes, it will detect whether all views are bound to relevant data, and then change the views. The publish-subscribe model used by Vue is point-to-point data binding.

Vue’s data binding has only two steps, compile=>link.

I have been thinking about how Vue monitors user modifications to the Model. It wasn’t until I discovered that each attribute in Vue’s data has set and get attributes that I understood.

In normal times, we create an object and modify its properties, as follows:

var obj = {
 val:99
}
obj.val = 100;
console.log(obj.val)//100
Copy after login

There is no problem, but if you want If you monitor it, when I modify the properties of this object, I need to do something. What will you do?

Related thoughts

This requires the use of getters and setters.

Suppose I want to add a name attribute to a coder object, and every time I update the name attribute, I have to complete something. We can do this:

var Coder = function() {
 var that = this;
 return {
  get name(){
   if(that.name){
    return that.name
   }
   return '你还没有取名'
  },
  set name(val){
   console.log('你把名字修成了'+val)
   that.name = val
  }
 }
}
var isMe = new Coder()
console.log(isMe.name)
isMe.name = '周神'
console.log(isMe.name)
console.log(isMe)
Copy after login

Output:

You will find that the printed effect of this object and the top data object in Vue are the same, both have get and set attribute.

Let’s analyze the above code step by step, it’s very interesting.

We first create an object literal:

var Coder = function() {...}
Copy after login

Then cache this:

var that = this;
Copy after login

The next thing is the most important, we return an object back:

{
 
  get name(){...},
 
  set name(val){...}
 
}
Copy after login

As the name suggests, get is the value and set is Assignment, under normal circumstances, we use obj.prop to obtain and assign values, but there is a problem with this. How do I know that the value of the object has changed? So it’s the set’s turn to appear.

You can understand get and set as functions. Of course, you can only understand them this way. They are two completely different things.

Next create an instance of the coder, isMe; at this time, isMe does not have a name attribute. When we call isMe.name, we will enter get name(){...}, First determine whether isMe has a name attribute. If the answer is no, then add a name attribute and assign a value to it: "You haven't given a name yet"; if there is a name attribute, then return the name attribute.

After seeing this, you must know how to use get. Yes, you can think of get as a function that takes a value. The return value of the function is the value it gets.

I feel that the more important thing is the set attribute. When I assign a value to the instance:

isMe.name="周神"
Copy after login

At this time, it will enter set name(val) {...}; The formal parameter val is the value I assigned to the name attribute. In this function, I can do a lot of things, such as two-way binding! Because every change of this value must go through set, it cannot be changed by other methods, which is equivalent to a universal listener.

There is another way to achieve this function.

ES5’s object prototype has two new attributes __defineGetter__ and __defineSetter__, which are specially used to bind get and set to objects.

can be written like this:

var Coder = function() {
}
Coder.prototype.__defineGetter__('name', function() {
 if (this.name) {
  return this.name
 }else{
  return '你还没有取名'
 }
})
Coder.prototype.__defineSetter__('name', function(val) {
 this.name = val
})
var isMe = new Coder()
console.log(isMe.name)
isMe.name = '周神'
console.log(isMe.name)
console.log(isMe)
Copy after login

The effect is the same. It is recommended to use the following method, because it is written on the prototype, so it can Inherit and reuse.

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more thoughts on getters and setters caused by Vue.js, please pay attention to the PHP Chinese website for related articles!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles