대상, 원형, 계승
대상
대상을 생각하면 먼저 다음과 같이 만듭니다.
var p1 = {
name: 'xyx',
age: 22,
sayname: function(){
console.log(this.name);
}
};
p.sayname();//xyx
可是如果要创建很多个,则要重复以上代码很多次,现创建一个函数,通过调用函数来创建对象:
공장 모델
function people(name,age){
var p = {
name: name,
age: age,
sayname: function(){
console.log(this.name);
}
};
return p;// ,
}
var p1 = people("aa",11);
p1.sayname();//aa
var p2 = people("bb",11);
p2.sayname();//bb
구조 함수 모드
function people(name,age){
this.name = name,
this.age = age,
this.sayname = function(){
console.log(this.name);
}
};
var p1 = new people("aa",11);
p1.sayname();//aa
console.log( p1 instanceof people ); //true
注:
1.people是个函数, 当 new people()的时候就会把people做为构造函数,构造对象。
2.用people创建对象后,people函数里的this代表 people {name: "aa", age: 11}.
3.instanceof的作用是判断p1是不是people的实例
原型方式
1.函数也是对象,对象是有属性和值的,任何一个函数都有prototype这个属性,这个属性的值也是对象,叫原型对象
2.当创建一个对象后,该对象拥有创建者赋予的所有功能。同时该对象还有个额外的内部属性,指向构造函数的原型对象。
3.把所有对象使用的公共资源放在原型对象。
原型结构图
// Cake
function Cake(color,meterial){
this.color = color;
this.meterial = meterial;
}
// Cake
Cake.prototype = {
other: ' ',
sayname: function(){
console.log(" "+this.color+this.meterial);
}
}
var c1 = new Cake(" "," ");
c1.sayname();//
c1과 cake에는 다음과 같은 관계가 있습니다.
Cake.prototype===c1.__proto__;//Cake {}
Cake.__proto__;//function (){}
Cake.constructor;//Function() { [native code] }
Cake.prototype.__proto__ === c1.__proto__.__proto__;//Object {}
c1.prototype;//undefinded prototype
c1.constructor === Cake.prototype.constructor;//function cake(){}
다음과 같은 예가 있습니다.
// cake sayname, prototype sayname
function Cake(color,meterial){
this.color = color;
this.meterial = meterial;
this.sayname= function(){
console.log(this.color+this.meterial);
}
}
Cake.prototype.sayname = function(){
console.log(" "+this.color);
}
var c1 = new Cake(" "," ");//new c1 ,cake this c1
c1.sayname();//
물려받다
原型链对象继承:
function People(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.say = function(){
console.log(this.name + " ");
}
Student.prototype = new People();// people
Student.prototype.constructor = Student;
function Student(name,age,sex,grade){
People.call(this,name,age,sex);
this.grade = grade;
}
var s1 = new Student(" ",11," ",88);
数据继承(用于默认参数)
var p1 = {name: ' ', age: 1},
p2 = {name: ' ', sex: 'male'};
var newObj1 = $.extend(obj1, obj2); // obj2 obj1,obj1
var newObj2 = $.extend({}, obj1, obj2); // obj1
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
상속 후의 집행 순서텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.