对象每次new出来一个实例,都会在内存中新开辟一块空间
function Star(name,age){
this.name = name
this.age = age
// this.sing = function(){
// console.log('sing'); //console.log(zs.sing === ls.sing) false
// }
}
Star.prototype.sing = function(){
console.log('sing');
}
var zs = new Star('zs',20)
var ls = new Star('ls',21)
console.log(zs.sing === ls.sing) true
__proto__
var zs = new Star('zs',20) //系统会给对象添加一个__proto__ 执行我们构造函数的原型对象
console.dir(zs.__proto__ === Star.prototype);
//先看对象是否有方法,有就执行,因为对象__proto__存在,会去原型对象prototype身上查找
constructor
__proto__和prototype都有constructor
console.log(zs.__proto__); //有constructor
console.log(Star.prototype); //有constructor
console.log(zs.__proto__.constructor); //可以看出引用的构造函数
原型链
所有普通的 [[Prototype]] 链最终都会指向内置的 Object.prototype
原型扩展
Array.prototype.sum = function(){
var a = 1
var b = 2
var sum
sum = a + b
return sum
}
console.log(Array.prototype); //sum: ƒ ()
构造函数继承属性
function A(name,age){
this.name = name
this.age = age
}
function B(name,age,score){
//this指向B实例
A.call(this,name,age)
this.score = score
}
var star = new B('ls',21,80)
console.log(star);
原型对象继承方法
function A(name,age){
this.name = name
this.age = age
}
A.prototype.money = function(){
console.log("money");
}
function B(name,age,score){
A.call(this,name,age)
this.score = score
}
//B.prototype = A.prototype //问题:此时A的原型上面会有B扩展 money: ƒ () sum: ƒ ()
B.prototype = new A() //解决:此时A原型上不会有扩展,因为原型和对象实例是A上两个不同引用
B.prototype.constructor = B //并且还指回自己
B.prototype.sum = function(){
console.log(sum);
}
var star = new B('ls',21,80)
console.log(star);
console.log(A.prototype);
console.log(B.prototype.constructor);