new and instanceof Javascript

new and instanceof Javascript

本文关键字:Javascript instanceof and new      更新时间:2023-09-26

嗨,我是Javascript新手。我对这个新词和它在决定instanceof操作符输出中的作用有点困惑。

1。返回对象字面值

var Dog=function(){
return{legs:4,bark:alert("BOW!!")};};
var luna=Dog();
luna instanceof Dog;//why false here
false
var luna=new Dog();
luna instanceof Dog;//why false here
false

案例2:现在我没有返回对象字面量,而是什么都不做,

var Dog=function(){
};
var luna=Dog();
luna instanceof Dog
false
var luna=new Dog();
luna instanceof Dog;//why true here
true
var luna=Dog();
luna instanceof Dog;//why false here

因为你:

  1. 没有使用new操作符
  2. 返回一个简单对象
var luna=new Dog();
luna instanceof Dog;//why false here

因为您返回了一个简单对象,该对象覆盖了由new操作符创建的对象。

var luna=new Dog();
luna instanceof Dog;//why true here

因为你:

  1. 是否使用new操作符
  2. 没有覆盖返回值

使用function关键字创建类可能会令人困惑。当你在没有new关键字的情况下调用Dog()时,你所做的只不过是调用一个函数;不涉及类。

在情形1中,第一个luna只是Dog作为普通函数调用时的结果:{legs:4, bark: alert("BOW!!")},与作为类的Dog无关。第二个luna也是如此。由于Dog返回一个对象,它覆盖了通常由new创建的"类"实例。

在Case 2中,第一个luna就像Case 1中的第一个luna一样,是一个普通对象。但是第二个lunaDog的实例,因为使用了new关键字,这意味着Dog被视为类而不是函数,并且Dog不返回任何内容。

(另外,您应该将对象更改为{legs: 4, bark: function() { alert("BOW!!"); }})

Case 1:

var Dog=function(){
return{legs:4,bark:alert("BOW!!")};};
var luna=Dog();
luna instanceof Dog;
false

这里你没有实例化任何东西,它只是一个返回值的函数:一个普通对象。这大致相当于:

var Dog=function(){
return new Object();
}

返回值的构造函数是Object: luna.constructorObject()函数

var luna=Dog();
luna instanceof Dog;
false

var luna=new Dog();
luna instanceof Dog;
false

你不能实例化一个返回值的函数

案例2:

var Dog=function(){
};
var luna=Dog();

它被作为一个函数调用,一个不返回任何东西的函数,实际上它返回undefined

luna instanceof Dog
false 

因为undefined不是任何对象的实例

var luna=new Dog();

创建一个新的Object, luna.constructorDog()

luna instanceof Dog;//luna is an object here
true

new操作符用于指定函数应该做什么:没有它,它返回一些东西(或undefined),有了它,它从构造函数(这里是Dog)实例化一个新对象