怪我阅读理解考零分,这书看着打脑壳。
原型对象:
function laptop(color, brand, price){
this.color = color;
this.brand = brand;
this.price = price;
}
console.log(laptop.prototype);
输出结果是一个原型对象,内部有一个constructor指向原函数。
console.log(laptop === laptop.prototype.constructor) //true
console.log(laptop === laptop.prototype); // false
哭,这书上解释的跟绕口令一样 :
“当我们创建函数时,javascript会自动创建一个原型对象,被创建函数会默认有一个ptototype属性指向原型对象,原型对象也有一个constructor属性指向原函数。
因此对于对象的构造函数存在一个原型对象可通过prototype访问。”
难道是说: 1.prototype属性,从创建函数指向它的原型对象。laptop 与 laptop.prototype,他们不是同一个东西。
2.constructor属性,从原型对象指向原函数。laptop 和 laptop.prototype.constructor是同一个东西。
3.改变原型对象的属性后,原函数并不会改变,但是用该函数实例化的对象可以改变。
function laptop(color, brand, price){
this.color = color;
this.brand = brand;
this.price = price;
this.program = function(){
console.log("用来玩游戏");
}
}
var laptop1 = new laptop ("white", "apple", "10000");
laptop.prototype.size = 15;
laptop.prototype.game = function(){
console.log("用来画画");
} //只在原型对象上添加了新属性,原函数不会改变
console.log(laptop.prototype)
console.log(laptop);
console.log(laptop.size)
console.log(laptop1.size);
书上写“在获取原型对象后可以通过修改原型对象的方法和属性来改变所有以该原型对象为原型的对象的方法和属性。”
哭。
或许可能大概它的意思是:实例化后如果发现原函数没有这个属性,再到原型对象上找。
实现了:改变原型对象的属性后,原函数并不会改变,但是用该函数实例化的对象可以改变。
原型对象的继承:
“为构造函数指定一个原型对象,用这个构造函数创建的对象就有原型对象的所有属性和方法,这就是继承”
为构造函数指定一个原型对象? (为原型对象指定一个构造函数 )??
同样,实例化后原函数上没有的,再去原型对象上找。
ul1 = new ul();
console.log(ul1.color); // white
console.log(ul1.brand); //acer
console.log(ul1.size); //15