//=====第一题:下面代码输出结果
function C1(name) { //没有传参 name 为 undefined
if (name) {
this.name = name;
}
}
function C2(name) {
//没有传参 name 为 undefined
this.name = name;
//增加name私有属性,值为undefined
}
function C3(name) {
//没有传参 name 为 undefined
this.name = name || 'join';
// 增加name私有属性,值为join
}
C1.prototype.name = 'Tom';
C2.prototype.name = 'Tom';
C3.prototype.name = 'Tom';
//new C1().name 没有私有,拿到的公有name =>‘tom’
//new C2().name 有私有,值为undefined
//new C3().name 有私有,值为‘join’
alert((new C1().name) + (new C2().name) + (new C3().name));
//函数实例化,参数不传为undefined
//new C1().name => 因为name为undefined,所以当前函数内没有name属性,只能去原型对象去找所以结果为"Tom"
//new C2().name => 因为name为undefined,所以当前函数内拥有私有属性name为 undefined,结果为undefined
//new C3().name => 因为name为undefined,所以当前函数内拥有私有属性name为 “join”,结果为’join’
//=====第二题:下面代码输出结果
function Fn(num) {
this.x = this.y = num;
}
//Fn.prototype改变指向
Fn.prototype = {
x: 20,
sum: function () {
console.log(this.x + this.y);
}
};
let f = new Fn(10);//f是fn的实例 私有属性 x=y=10
console.log(f.sum === Fn.prototype.sum);
f.sum();//这里执行this 是f, f.x+f.y=20
Fn.prototype.sum(); //这里执行this 是Fn.prototype Fn.prototype.x+Fn.prototype.y=20+undefined=NaN
console.log(f.constructor);
//f没有私有的constructor,去找f.__proto__也就是Fn.prototype,由于改变指向不是原来的prototype了。所以没有constructor,再继续往上找,找普通对象的__proto__,也就是找Object的原型,Object的原型shang的constructor 指向Object
//======第三题 下面输出结果
function Fn() {
let a = 1;
this.a = a;
}
Fn.prototype.say = function () {
this.a = 2;
}
Fn.prototype = new Fn; //先创建new Fn
let f1 = new Fn;
Fn.prototype.b = function () {
this.a = 3;
};
console.log(f1.a);//f1指向new Fn=>f1.a就是Fn里的a=>输出 1
console.log(f1.prototype);// f1是一个实例对象,没有prototype,new Fn是个对象也没有prototype,在往上找都是原型对象,没有prototype,所以结果就是undefined
console.log(f1.b);=>f1里面没有到prototype原型上找=>function(){ this.a=3}
console.log(f1.hasOwnProperty('b'));//hasOwnProperty()检测‘b’是不是f1的私有属性,显然‘b’不是f1的私有属性
console.log('b' in f1);//'b'在f1的原型对象上,属于f1的公有属性
console.log(f1.constructor == Fn);//f1和Fn指向同一个 propertype原型
//=====第四题 下面输出结果
function fun() {
this.a = 0;
this.b = function () {
alert(this.a);
}
}
fun.prototype = {
b: function () {
this.a = 20;
alert(this.a);
},
c: function () {
this.a = 30;
alert(this.a)
}
}
var my_fun = new fun();
my_fun.b();//0
my_fun.c(); //30