打字稿instanceof返回false

时间:2020-01-13 23:50:54

标签: typescript

class Department {
 name: string;

 constructor(n: string) {
     this.name = n; 
 }

 describe(this: Department){
     console.log('department: ' +this.name);
 }
}

const frontend = new Department('frontend');
frontend.describe();

const frontendCopy = {name: 'Jay', describe: frontend.describe};

frontendCopy.describe();
console.log(frontendCopy instanceof Department);
console.log(frontend instanceof Department); 

您好,我是初级前端工程师 我想知道为什么

console.log(部门的frontendCopy实例);

打印错误。 如果frontendCopy不是Department的实例,则不应运行frontendCopy.describe()?

,但frontend.describe()和frontendCopy.describe()均有效。

3 个答案:

答案 0 :(得分:2)

要将frontendCopy设为Department的实例,您需要使用new Department(:string)

class Department {
    name: string;

    constructor(name: string) {
        this.name = name; 
    }

    describe() {
        console.log('department: ' + this.name);
    }
 
    clone(): Department {
        return new Department(this.name);
    }
}

const department = new Department('frontend');
department.describe();

const departmentCopy = department.clone();
departmentCopy.describe();

console.log(department instanceof Department);
console.log(departmentCopy instanceof Department);

答案 1 :(得分:2)

departmentdepartmentCopy的创建方式不同,因此对它们的处理方式也不同。

JavaScript使用所谓的“原型OOP”(新的面向类的语法实际上只是语法糖)。这意味着,每个对象都有其原型。 instanceof运算符通过利用这一点进行工作-实际上,它检查其左参数的原型链以找到满足右参数的内容。

使用new Department创建值时,将基于department本身创建Department的原型。因此,department instanceof Department检查department.prototype,发现它基于Department,并返回true

但是,基于对象文字创建值时,它不与Department连接-它的原型只是Object(复制了所有{{都没关系1}}域从Departmentdepartment-原型是独立设置的)。因此,departmentCopy看到departmentCopy instanceof Department不在原型链中,并返回Department

关于false起作用的原因-这很简单:因为您创建的departmentCopy.describe()具有属性departmentCopy是可调用的(即函数)。该属性的来源无关紧要-类定义或手动设置。

答案 2 :(得分:0)

非常抱歉您等待我的回复。 我找到了一些文档,它为我解释了很多有关类和继承的知识。

在下面我链接的“了解私人”部分中,即使动物和雇员也具有相同的结构,这是完全不同的。

为什么我提到关于类和继承主题的示例似乎很奇怪,但是我认为我们可以在这里得到一些提示。

[https://www.typescriptlang.org/docs/handbook/classes.html#understanding-private][1]

顺便说一句,谢谢您的所有回答和评论。 我的话可能会有误解,您可以自由离开。

再次感谢!

相关问题