js 진급 학습 의 - 대상 지향 (1)
2133 단어 js
대상 을 구축 하 는 방식 은 모두 세 가지 가 있 습 니 다.
//1.
// :
function Person(name,sex,age){
var obj = new Object();
obj.name = name;
obj.sex = sex;
obj.age = age;
obj.eat = function(){
console.log(" ");
}
return obj;
}
var person = createObj(" "," ",28);
console.log(person);
//2. ( 、 )
var person = {
name:" ",
sex:" ",
age:30,
eat:function(){
console.log(" ");
},
say:function(){
console.log(" ");
}
};
console.log(person);
//3.
//1)、 ( )
//2)、
// : ()
// : new (); new , this , ,this 。
function Person(){
this.name = " ";
this.sex = " ";
this.age = 30;
this.eat = function(){
console.log(" ");
}
}
//Person.abc = "123"; // : . =
var person = new Person();
// : .
console.log(person);
//console.log(Person.abc); // : .
대상 에 게 공유 하 는 방법 추가:
2
// ( )
// : ,
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
this.hobby = [" "," "];
}
// 2 :
//1.
Person.prototype.eat = function(){
console.log(" ");
}
Person.prototype.say = function(){
console.log(" ");
}
console.log(Person.prototype);
//2.
Person.prototype = {
constructor:Person,
eat:function(){
console.log(" ");
},
say:function(){
console.log(" ");
}
};
console.log(Person.prototype);
//
var person1 = new Person(" "," ",30);
console.log(person1);
var person2 = new Person(" "," ",28);
// ,