原型prototype
-
定义: 原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过该构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。
-
利用原型特点和概念,可以提取共有属性。
gidle.prototype.characteristic = "prettygirl";
function gidle (name, age) {
this.name = name;
this.age = age;
this.fansname = neverland;
}
var shua = new gidle('花树叶', 00);
// gidle的共有属性的名字是prettygirl;
- 对象如何查看原型 ——> 隐形属性__proto__
(表示尽量别修改
gidle.prototype.characteristic = "prettygirl";
function gidle () {
// var this{
// __proto__ : gidle.prototype
// }
}
var susu = {
name : "susu";
}
var shua = new gidle();
gidle.__proto__ = susu;
gidle.prototype.name = 'gidle';
function gidle () {
// var this{
// __proto__ : gidle.prototype
// }
}
var shua = new gidle();
gidle.prototype.name = '娃'//娃
gidle.prototype = {
name : '娃';//gidle
//该写法意思是直接更换prototype的对象,而不是更改prototype所属name,所有prototype.name不变
}//如果将此语句放在var shua前面,则output: 娃
input : shua.name
gidle.prototype.name = 'gidle';//————2
function gidle () {//————1//预编译提升
// var this{
// __proto__ : gidle.prototype
// }
}
gidle.prototype = {//————4
name : '娃'
}
var shua = new gidle();//————3,调用this.__proto__ : gidle.prototype(即4)
input : shua.name
Object.prototype ———>所有对象的最终原型
- 对象如何查看对象的构造函数 ——> constructor
原型链
-
如何构成原型链
-
原型链上属性的增删改查
-
绝大多数对象的最终都会继承自Object.prototype
-
Object.create(原型)
Object prototype may only be an Object or null;
Object.create(null) ——> Object : No Properties
- 重写
Object.prototype.toString = function(){
}
gidle.prototype = {
toString: function(){
return '小颗粒';
}
}
function gidle(){
}
var yuqi = new gidle();
call/apply⭐
本质: 借用别人的函数实现自己的功能
作用: 改变this指向
function Gidle(name, age){
//call让this == Gidle
this.name = name
this.age = age
}
var minnie = new Gidle('minnie', 18);
var gidle = {
}
Gidle.call(gidle,'minnie','18');
input: gidle
output: {name: 'minnie', age: '18'}
function Person(name, age, sex){
this.name = name
this.age = age
this.sex = sex;
}
function Student(name, age, sex, tel, grade){
Person.call(this, name, age, sex);//var this = {name: "", age: "", sex: ""}
this.tel = tel;
this.grade = grade;
}
var student = new Student('奶味蓝', 1, 1, 1, 1);
区别: 传参形式不同
call 需要把实参按照形参的个数传进去
apply 需要传一个arguments
function print(){
var marty = {
name : "marty",
printName : function(){console.log(this.name);}//marty
}
var test1 = {name : "test1"};
var test2 = {name : "test2"};
marty.printName.call(test1);//test1
marty.printName.apply(test2);//test2
}
print();