原型链的顶端 object.prototype
不是所有的对象都继承Object.prototype
例如
var obj = Object.create(null)obj.num = 1;console.log(obj);
结果:
call/apply
// call/apply 更改this的指向
function Car(brand,color) {
this.brand = brand;
this.color = color;
this.run = function () {
console.log('running');
}
}
var newCar = {
displacement:"3.0"
};
// Car.call(newCar,'Benz','red');
Car.apply(newCar,['Benz','red']);
console.log(newCar);
var car = new Car('Benz','red');
console.log(car);
课后作业
// 年龄为多少岁姓名为某买了一辆什么颜色什么品牌的车
function Car(opt){
this.color = opt.color;
this.brand = opt.brand;
}
function Person(opt){
Car.apply(this,arguments);
this.names = opt.names;
this.ages = opt.ages;
this.select = function(){
console.log(`年龄${this.ages}名字为:${this.names}买了一辆${this.color}色的${this.brand}`);
}
}
var person = new Person({names:'小明',ages:15,color:'red',brand:'benz'});
console.log(person);
console.log(person.select());
参考答案
function Car(brand,color,displacement) {
this.brand = brand;
this.color = color;
this.displacement = displacement;
this.info = function () {
return '排量为' + this.displacement + '的' + this.color + this.brand
}
}
function Person(opt) {
Car.apply(this,[opt.name,opt.color,opt.displacement]); //此时this等于实例化的 p apply可以理解成借用函数 借用car里面的参数和方法
this.name = opt.name;
this.age = opt.age;
this.say = function () {
console.log('年龄'+this.age+'岁姓名为'+this.name+'卖了一辆'+this.info());
}
}
var p = new Person({
brand:'奔驰',
color:'红色',
displacement:'3.0',
name:'张三',
age:'25'
})
p.say();
