Skill instances of properties and methods are Shared in JavaScript via prototype properties

  • 2020-05-16 06:14:42
  • OfStack

The specific code is as follows:


// Define a function
function people(name,sex,age){
 this.name = name;
 this.sex = sex;
 this.age = age;
}
 
// Shared isStudent with sayName methods
people.prototype = { 
 isStudent:true,
 sayName:function(){
  alert(this.name);
 }
}
 
var people1 = new people(' Han meimei ',' female ',16);  // Instantiate object 1
var people2 = new people(' Li lei ',' male ',17);    // Instantiate object 2
 
// Let two objects say their names by sharing methods
people1.sayName();
people2.sayName();
 
// They are all students according to the Shared parameters
if(people1.isStudent == people2.isStudent)alert(' They are all students ');

This article also mentioned some knowledge of javascript objects, which should be easy to understand. If you really do not understand the words can be a little baidu 1.


Related articles: