js继承

上个例题:

var F=function(){};

Object.prototype.a=function(){};

Function.prototype .b=function(){};

var f=new F();

正确答案: A 

A  f能取到a,但取不到b

B  f能取到a,b

C  F能取到b,不能取到a

D  F能取到a,不能取到b

解析:这个问题涉及到js的原型继承

1.  f.__proto__ === f[的构造函数].prototype === F.prototype

2.  F.prototype.__proto__ ===  (F.prototype)[的构造函数].prototype ===  Object.prototype (所以a能够 通过f.a访问)

3. f.constructor === F

4. F.__proto__ === F[的构造函数].prototype === Function.prototype (所以b可以通过, f.constructor.b访问到)

注意:

(F.prototype)[的构造函数] === Object

F[的构造函数] === Function

多啰嗦一句( js 的继承靠的是__proto__ ,并不是prototype)

还有每一个函数的默认原型(即函数的prototype)都是Object的实例

这句话也就是说函数的prototype._proto_是指向Object.prototype

建议去看js红皮书的内容



链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6

来源:牛客网

functionTreeNode(x) {

this.val = x;

this.left =null;

this.right =null;

}

functionreConstructBinaryTree(pre, vin)

{

if(vin.length === 0)

returnnull;

varroot = 0, i, j;

varleft_pre = [], right_pre = [], left_in = [], right_in = [];

varhead =newTreeNode(pre[0]);

for(i = 0; i < vin.length; i++){

if(vin[i] === pre[0]){

root = i;

break;

}

}

for(j = 0; j < root; j++){

left_pre.push(pre[j+1]);

left_in.push(vin[j]);

}

for(j = root + 1; j < vin.length; j++){

right_pre.push(pre[j]);

right_in.push(vin[j]);

}

head.left = reConstructBinaryTree(left_pre, left_in);

head.right = reConstructBinaryTree(right_pre, right_in);

returnhead;

}

module.exports = {

reConstructBinaryTree : reConstructBinaryTree

};

你可能感兴趣的:(js继承)