嗨,我是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
因为你:
- 没有使用
new
操作符 - 返回一个简单对象
var luna=new Dog(); luna instanceof Dog;//why false here
因为您返回了一个简单对象,该对象覆盖了由new
操作符创建的对象。
var luna=new Dog(); luna instanceof Dog;//why true here
因为你:
- 是否使用
new
操作符 - 没有覆盖返回值
使用function
关键字创建类可能会令人困惑。当你在没有new
关键字的情况下调用Dog()
时,你所做的只不过是调用一个函数;不涉及类。
在情形1中,第一个luna
只是Dog
作为普通函数调用时的结果:{legs:4, bark: alert("BOW!!")}
,与作为类的Dog
无关。第二个luna
也是如此。由于Dog
返回一个对象,它覆盖了通常由new
创建的"类"实例。
在Case 2中,第一个luna
就像Case 1中的第一个luna
一样,是一个普通对象。但是第二个luna
是Dog
的实例,因为使用了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.constructor
是Object()
函数
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.constructor
是Dog()
luna instanceof Dog;//luna is an object here
true
new操作符用于指定函数应该做什么:没有它,它返回一些东西(或undefined
),有了它,它从构造函数(这里是Dog
)实例化一个新对象