1.下面代码运行的结果
//1. 答案: 0 30
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
2.写出下面代码执行输出的结果
// 2.答案:'Tomundefinedjoin'
function C1(name) {
if (name) {
this.name = name;
}
}
function C2(name) {
this.name = name;
}
function C3(name) {
this.name = name || 'join';
}
C1.prototype.name = 'Tom';
C2.prototype.name = 'Tom';
C3.prototype.name = 'Tom';
alert((new C1().name) + (new C2().name) + (new C3().name));//'Tomundefinedjoin'
//(new C1().name)没有传递参数,所以没有私有name属性,取原型上的公有name属性
//(new C2().name)没有传递参数,默认值为undefined,取私有name属性值为undefined
//(new C3().name)没有传递参数,默认值为undefined,取私有name属性,如果值为undefined则取值join
3.下面代码运行的结果?
//3. 答案:
// 1 undefined
// ƒ () {this.a = 3;}
// false true true
// ƒ () {this.a = 2;}
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);//ƒ () {this.a = 3;}
console.log(f1.hasOwnProperty('b'));//false
console.log('b' in f1);//true
console.log(f1.constructor == Fn);//true
console.log(f1.say);//ƒ () {this.a = 2;}
4.写出下面代码执行输出的结果
// 4.答案: 2 4 1 1 2 3 3 3
function Foo() {
getName = function () {
console.log(1);
};
return this;
}
Foo.getName = function () {
console.log(2);
};
Foo.prototype.getName = function () {
console.log(3);
};
var getName = function () {
console.log(4);
};
function getName() {
console.log(5);
}
Foo.getName();//2
getName();//4
Foo().getName();//1
getName();//1
new Foo.getName();//2
(new Foo).getName();//3
new Foo().getName();//3
new new Foo().getName();//3
5.代码输出的结果
let obj = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push
}
obj.push(1);
obj.push(2);
console.log(obj);
// {2:1,3:2,length:4,push:f push()}