function Fn() {
this.x = 100;
this.y = 200;
this.getX = function () {
console.log(this.x);
}
}
Fn.prototype = {
y: 400,
getX: function () {
console.log(this.x);
},
getY: function () {
console.log(this.y);
},
sum: function () {
console.log(this.x + this.y);
}
};
Fn.prototype.getX = function () {
console.log(this.x);
};
Fn.prototype.getY = function () {
console.log(this.y);
};
var f1 = new Fn;
var f2 = new Fn;
console.log(f1.getX === f2.getX);
console.log(f1.getY === f2.getY);
console.log(f1.__proto__.getY === Fn.prototype.getY);
console.log(f1.__proto__.getX === f2.getX);
console.log(f1.getX === Fn.prototype.getX);
console.log(f1.constructor);
console.log(Fn.prototype.__proto__.constructor);
f1.getX(); // this=>f1 x = 100
f1.__proto__.getX(); // this=>f1.__proto__(Fn.prototype) x : undefined
f2.getY(); // this=>f2 y=200
Fn.prototype.getY(); // this=>Fn.prototype y=400
f1.sum();//this=>f1 f1.x+f1.y=300
Fn.prototype.sum(); //this=>Fn.prototype undefined+400=NaN
分析:f1,f2分别为Fn的两个实例(私有属性互相独立,但原型上的属性是公有的),里面都有各自的私有属性,x,y,getX(),所以
1.
f1.getX === f2.getX结果为false;
2.
f1.getY === f2.getY为原型上公有的方法,结果为true;
3.
f1.proto等于Fn.prototype,f1.proto.getY === Fn.prototype.getY结果为true
4.
f1.proto.getX === f2.getX原型上跟私有的方法肯定不是同一个,结果为false
5.
f1.getX === Fn.prototype.getX理由同上,false
6.
f1.constructor,实例没有自己的constructor,但实例对象可以继承原型对象的属性,所以实例对象也拥有constructor属性,同样指向原型对象对应的构造函数,即Fn.prototype.constructor ,结果为ƒ Object() { [native code] }
7.
Fn.prototype.proto.constructor,Fn的原型是对象类型,他的proto指向他的原型对象的prototype属性,即Fn.prototype.proto=Object.prototype,Object.prototype.constructor为本身ƒ Object() { [native code] }
this指向问题,在方法执行前看有没有点,有的话点前面是谁this就是谁,没有的话非严格模式下就是window(严格模式下为undefined)
function Fn() {
this.x = 100;
this.y = 200;
this.getX = function () {
console.log(this.x);
}
}
Fn.prototype.getX = function () {
console.log(this.x);
};
Fn.prototype.getY = function () {
console.log(this.y);
};
var f1 = new Fn; // x=100 y=200 getX->100 公有getY 200
var f2 = new Fn; // x=100 y=200 getX->100 公有getY 200
console.log(f1.getX === f2.getX); // false
console.log(f1.getY === f2.getY); // true
console.log(f1.__proto__.getY === Fn.prototype.getY); // true
console.log(f1.__proto__.getX === f2.getX); // false
console.log(f1.getX === Fn.prototype.getX); // false
console.log(f1.constructor); // Fn
console.log(Fn.prototype.__proto__.constructor); // Object
f1.getX(); // 100
f1.__proto__.getX(); // undefined
f2.getY(); // 200
Fn.prototype.getY(); // undefined
网友评论