开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情
prototype
function Handphone() {
}
//prototype
console.log(Handphone.prototype)
原型prototype其实是function对象的一个属性
我们通过prototype去绑定属性,看看能否访问到
function Handphone(color, brand) {
this.color = color;
this.brand = brand;
this.screen = '18.9';
this.system = 'Android';
}
//prototype绑定属性
Handphone.prototype.rom = '64G';
Handphone.prototype.ram = '6G';
var hp1 = new Handphone('red', '小米');
var hp2 = new Handphone('black', '华为');
console.log(hp1.rom)
console.log(hp2.ram)
- 这个
prototype是定义构造函数构造出的每个对象的公共祖先 - 所有被该构造函数构造出的对象都可以继承原型上的属性和方法
访问的时候,当this上定义的话,就不会在访问在原型上重新定义的属性
function Handphone(color, brand) {
this.color = color;
this.brand = brand;
this.screen = '18.9';
this.system = 'Android';
}
Handphone.prototype.rom = '64G';
Handphone.prototype.ram = '6G';
Handphone.prototype.screen = '16:9';
var hp1 = new Handphone('red', '小米');
var hp2 = new Handphone('black', '华为');
console.log(hp1.screen)
console.log(hp2.screen)
我们通过prototype定义了screen为 16.9,输出结果居然是 18.9
原型的作用
我们在实例化对象增加属性时通过prototype访问
function Test() {
}
Test.prototype.name = 'prototype';
var test = new Test();
test.num = 1;
console.log(Test.prototype)
输出是没有看到结果了,他这个num是放到this上面,这样增加是不行的
delete 也不可行
function Test() {
}
Test.prototype.name = 'prototype';
var test = new Test();
delete test.name;
console.log(Test.prototype)
通过实例化对象来进行增,删,改自己的祖先是不可行的
function Handphone(color, brand, system) {
this.color = color;
this.brand = brand;
this.system = system;
}
console.log(Handphone.prototype)
输出一个constructor,我们只需知道constructor对应的是构造函数本身