1 function createPerson(name,age,job){ 2 var o = new Object(); 3 o.name = name; 4 o.age = age; 5 o.job = job; 6 o.sayName = function(){ 7 console.log(this.name); 8 } 9 return o;10 }11 12 var person1 = createPerson("Nicholas",29,"SoftWare Engineer");13 var person2 = createPerson("Greg",23,"Doctor");
1 function Person(name,age,job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.sayName = function(){ 6 console.log(this.name); 7 }; 8 } 9 10 var person1 = new Person("Nicholas",29,"SoftWare Engineer");11 var person2 = new Person("Greg",23,"Doctor");
1 alert(person1.constructor == Person); //true2 alert(person2.constructor == Person); //true
1 console.log(person1 instanceof Object); //true2 console.log(person1 instanceof Person); //true
1 //当做构造函数使用 2 var person = new Person("Nicholas",29,"Software Engineer"); 3 person.sayName(); //Nicholas 4 5 //作为普通函数调用 6 Person("Greg",27,"Doctor"); 7 window.sayName(); //Greg 8 9 //在另一个对象的作用域中调用10 var o = new Object();11 Person.call(o,"Kristen",25,"Nurse");12 o.sayName(); //Kristen
1 console.log(person1.sayName == person2.sayName); //false
1 function Person(name,age,job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.sayName = sayName; 6 } 7 8 function sayName(){ 9 console.log(this.name);10 } 11日,12日,,,,,var person1 =, new 人(“尼古拉斯”,29日,“SoftWare 工程师”),13,,,,,var person2 =, new 人(Greg, 23日,“医生”);