第一题
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);
}
let f1 = new Fn;
let f2 = new Fn;
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) // obj
f1.getX() //100
f1.__proto__.getX() // undefined Fn.prototype里面没有x属性,然后向object的原型中个查找也没有x,则undefined
f2.getY(); // 找到了公有的getY,this指的是f2 //200
Fn.prototype.getY() //undefined
第二题
function C1(name) {
// name:undefined
if (name) {
this.name = name;
}
}
// new C1() 创建c1的实例,此时我们没有传值,所以函数中的name就是undefined ,new C1().name 私有属性中找不到,在公有中找到了name = tom
function C2(name) {
// name:undefined
// this.name = undefined
this.name = name
}
function C3(name) {
this.name = name || 'join'
}
C1.prototype.name = 'Tom';
C2.prototype.name = 'Tom';
C3.prototype.name = 'Tom';
// new C1().name => C1.prototype.name = 'tom'
alert((new C1().name) + (new C2().name) + (new C3().name));
// tom + undefined + join = tomundefinedjoin
第三题
function Fn(num) {
this.x = this.y = num;
}
Fn.prototype = {
x: 20,
sum: function () {
console.log(this.x + this.y);
}
}
let f = new Fn(10);
console.log(f.sum === Fn.prototype.sum); //true
f.sum(); // f.x + f.y = 10 + 10 = 20
Fn.prototype.sum(); // NaN
console.log(f.constructor); // object
console.log(Fn.prototype.constructor); // obj
第四题
function Fn() {
let a = 1;
this.a = a;
}
Fn.prototype.say = function () {
this.a = 2;
}
Fn.prototype = new Fn;
let f1 = new Fn;
Fn.prototype.b = function () {
this.a = 3;
}
console.log(f1.a); // 1
console.log(f1.prototype); // undefined
console.log(f1.b); //f()
console.log(f1.hasOwnProperty('b')); // false b是公有属性
console.log('b' in f1); //true b是不是f1的属性(无论公有还是私有)
console.log(f1.constructor == Fn); // true
第五题
(普通函数执行与构造函数执行,其中的不同以及相同点和this有哪些不同)
function Fn(n, m) {
this.x = n + m;
this.y = n - m;
let total = n * m;
return total;
}
Fn.prototype.say = function () {
console.log('say');
}
// 普通函数
let total = Fn(20, 10);
console.log(x) //30; window下的x,y
// 构造函数(类和实例)
let total1 = new Fn(20, 10);
console.log(total1.x); //30 此时this执行total这个实例