Copy the code code as follows:
//Constructor
function person(name, age) {
this.name = name;
this.age = age;
}
//Define person prototype, the attributes in the prototype can be referenced by custom objects
person.prototype = {
getName: function () {
return this.name;
},
getAge: function () {
return this.age;
}
}
Copy the code code as follows:
This requires the introduction of another concept - prototype. We can simply regard prototype as a template. The newly created custom objects are all copies of this template (prototype) (actually not a copy but a link. It’s just that this kind of link is invisible and gives people the impression that it is a copy).
JavaScript simulates the functions of classes through constructors and prototypes.
window.onload = function () {
person.prototype.sex = 'Male';
var fmj =new person('kkk', 22);
alert('First output:'+fmj.sex);
fmj.sex = 'Confidential';
alert('Second output:' + fmj.sex);
delete fmj.sex;
alert('The third output:' + fmj.sex);
//Output the results in the debug console.
//console.log(fmj.getAge());
}