4.2-读代码
1 以下代码输出为
const arr = [];
const testObj = {};
console.log(arr === ""); // false
console.log(arr == ""); // true
arr.toString = () => 1;
console.log(arr === 1);// false
console.log(arr == 1);// true
arr.valueOf = () => 2;
console.log(arr == 2);// true
arr.valueOf = () => testObj;
console.log(arr == testObj); // false
valueOf 是做什么的?
// valueOf
2 以下代码的输出内容?
let a = 0;
const obj = {
a: 1,
b: function() {
console.log(this.a);
}
}
const obj1 = {
a: 2
}
const fun = obj.b;
fun()
fun.apply(obj)
fun.bind(obj1).apply(obj)
const fun1 = fun.bind(obj1)
new fun()
// undefined 1 2 undefined
以下代码输出为
function func() {
this.name = "Hellen";
}
console.log(typeof func.prototype);
func.prototype.getName = function() {
console.log(this.name);
}
const Obj = {};
Obj.__proto__ = func.prototype;
func.call(Obj);
if (Obj.getName) {
console.log("yes");
Obj.getName();
}
console.log("end");
// object yes Hellen end
以下代码输出是?
function func(source) {
var target = {};
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (typeof source[key] === 'object') {
target[key] = func(source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
}
var a = { a1: "a1", a2: { b1: "b1", b2: "b2" }, a3: undefined, a4: null, a5: 1 };
var b = func(a);
console.log(b);
// {a1: "a1", a2: {b1: "b1", b2: "b2"}, a3: undefined, a4: {}, a5: 1}
function setname(name){
this.name = name
}
setname.prototype.printName = function(){ console.log(this.name) }
let a = new setname("cc")
a.name = "dd"
a.__proto__.name = "ee"
a.__proto__.printName() // ?
a.printName() // ?
// ee dd