What is a constructor
Keywords:
Vue
Attribute
React
What is a constructor
- vue
- react
- You can get a new object through new. It's the constructor
The introduction of this
<script>
// In the function, whoever this represents calls this function points to
function add(){
var a=10;
var b=20;
console.log('this On behalf of:',this);//this here points to window
}
add();//Generally, the direct call is called by window
var list = {
start:function(){
console.log('this point'+this);
}
}
list.start();//this points to list
</script>
create object
<script>
// Create objects directly (literally)
// var vog = {
// color:'red',
// age = 2
// }
// Using the new keyword to create an object
var date = new Date();
//Date is a special function used to create objects called constructors
var reg = new RegExp('web','i');//RegExp
// Custom constructor
// Define a constructor to create cat cat objects
function MadeCat(name,age,addr){
this.name=name
this.age=age
this.addr=addr
// this here points to MadeCat
}
// Create a cat object based on its name, age and origin
var cat = new MadeCat('Muppet',2,'U.S.A');
// Call the function. At this time, this points to MadeCat
// Generate a new cat by calling functions and passing parameters
console.log(cat);
</script>
Constructor
<script>
// Prototype of constructor
// Define a constructor to create an object for cat
function MadeCat(name, age, addr) {
this.name = name,
this.age = age,
this.addr = addr;
// this here points to MadeCat
}
// MadeCat.prototype points to the prototype of MadeCat
console.log(MadeCat.prototype);
MadeCat.prototype.color='white';//Add properties to the prototype (change constructor for short)
MadeCat.prototype.say = function(){
console.log('Meme');
}
// Create a cat object, instantiate it
var cat = new MadeCat('Xiao Bai',2,'China');
console.log(cat);
cat.say();
// Madecat. Prototype = = = cat. \
/**
Conclusion:
1.Constructors, defining functions
2.Understand the direction of this, which points to the caller
3.Generate objects through functions (in short, add parameters to them and then
Assign these attributes and attribute values to a variable, which is an object)
4.Use prototype to select function prototype
Add the property or function you want to add)
Prototypes: 1. All constructors have corresponding prototypes
2.For attribute methods defined on prototypes, instances will have them
3.How to access, through the constructor.protoTypr
And instance__
*/
</script>
Prototype of constructor
- Method of prototype pointing to constructor
- Principle through prototype to select the prototype of the constructor, add, delete and modify it
Prototype application scenario
In vue, define a variable $http according to the prototype and put the encapsulated method in
get and post methods can be obtained through this.$http direct access to the prototype
Vue.prototype.$http = {
get,
post
};
Posted by ghurty on Wed, 27 Nov 2019 13:11:09 -0800