new and instanceof Javascript
new and instanceof Javascript
嗨,我是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
)实例化一个新对象
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 使用php或javascript从facebook相册URL中删除多余的部分
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在JavaScript中将字符串转换为函数引用
- 模糊事件的Javascript测试
- Javascript更改图标
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何使用WCF服务和javascript表单post上传.doc文件
- javascript结合了数组和字典
- 这是什么 ==- javascript 运算符
- 从javascript创建一个列表
- 无法在通过jQuery的ajax加载的页面中执行javascript
- Javascript:selenium Web驱动程序isDisplayed()不工作
- 如何通过ajax刷新JSF填充的javascript变量
- 如何在Javascript中将JSon对象转换为数组
- Javascript生成的表单未提交
- 使用javascript将动态表从一个html页面打印到另一个html页
- 通过javascript重定向html传递php变量