0302
1. 选择题: 选出以下正确项
const Pencil = function() {};
const redPencil = new Pencil();
a. Pencil.__proto__.constructor === Pencil
b. redPencil.__proto__.constructor === Pencil
c. redPencil.__proto__.__proto__ === Object.prototype
d. redPencil.__proto__.__proto__ === Function.__proto__.__proto__
(b、c、d)
- (a)constructor
function Foo() {}
Foo === Foo.prototype.constructor //true
拓展:
-
new
对函数进行实例化的过程
(1)let f = {}
//创建一个新的内存空间
(2)f.__proto__ = Foo.prototype
//f 继承 Foo的原型
(3)Foo.call(f, 'Xiaoming', 18)
//执行Foo函数,将 name, age 参数传入Foo中执行,此时函数内部 this 为 new 创建的 f 对象
function Foo(name, age) {
this.name = name;
this.age = age;
}
Foo.prototype.greet = function() {
console.log("Hello~")
};
let f = new Foo("Xiaoming", 18);
f.greet() //Hello~
2. 编程题(1)
实现可以反转字符串的函数方法
- 数组
reverse()
方法
- 数组
function reverse(str) {
return str.split('').reverse().join('');
}
- 自己实现
function reverse(str) {
let arr = str.split("");
let length = arr.length;
let endIndex = length % 2 === 0 ? length / 2 - 1 : (length - 1) / 2 - 1;
for (let i = 0; i <= endIndex; i++) {
[arr[i], arr[length - 1 - i]] = [arr[length - 1 - i], arr[i]];
}
return arr.join("");
}
3. 编程题(2)
实现可以撤销的 Promise 方法
function createCancelablePromise(promise) {
let isCanceled = false;
const cancelablePromise = new Promise((resolve, reject) => {
promise
.then(value => {
isCanceled ? reject({ isCanceled: true }) : resolve(value);
})
.catch(error => {
isCanceled ? reject({ isCanceled: true }) : reject(error);
});
});
return {
promise: cancelablePromise,
cancel() {
isCanceled = true;
}
};
}
//测试
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("value1");
}, 500);
});
let cancelbleP = createCancelablePromise(p);
cancelbleP.promise.then(value => {
console.log("value",value);
}).catch(err => {
console.log("err",err)
});
cancelbleP.cancel(); //取消异步操作
//err { isCanceled: true }
网友评论