原型
- 原型 -- proto -- 是实例化以后的结果,就是一个容器装prototype的。
- 原型prototype其实是function对象的一个属性,打印出来,结果它也是对象。 -这个prototype 是定义构造函数构造出的每个对象的公共祖先
- 所有被该构造函数构造出来的对象都可以继承原型上的属性和方法
- 当我们需要写死的时候,写到原型上
- constructor -> 构造函数本身,可以在原型中更改的。
- 如果实例化对象上没有找到这个属性,会沿着__proto__:xxx.prototype,继续向下寻找。
- proto 是可以被更改的
function Handphone(color,brand) {
this.color = color;
this.brand = brand;
this.system = "Android";
}
Handphone.prototype.rom = "61G";
Handphone.prototype.ram = "6G";
Handphone.prototype.screen = "16 : 9";
Handphone.prototype.system = "Android";
Handphone.prototype.call = function(){
console.log("I am calling somebody");
}
var hp1 = new Handphone("red","小米");
var hp2 = new Handphone("black","华为");
console.log(hp1.rom);
console.log(hp2.ram);
hp2.call();
原型增删改查问题
function Test() {
this.name = "this";
}
Test.prototype.name = "prototype";
var test = new Test();
// console.log(test.name);// 查找没有限制
test.num = 1;
console.log(Test.prototype,test);// 实例出来的对象不能增加原型属性,增加到this上了
delete test.name;
console.log(Test.prototype,test);// 删除的是this 的name,不是原型的,方法也不行
test.name = "I am test";
console.log(Test.prototype,test);// 原型没有改,改变的是自己
(function () {
var Compute = function (opt) {
this.x = opt.firstNum;
this.y = opt.secondNum;
}
Compute.prototype = {
plus: function () {
return this.x + this.y;
},
minus: function () {
return this.x - this.y;
},
mul: function () {
return this.x * this.y;
},
div: function () {
return this.x / this.y;
}
}
window.Compute = Compute;
})();
var comput = new Compute({
firstNum: 1,
secondNum: 2,
});
console.log(comput.plus());