JavaScript函数和新运算符 [英] JavaScript functions and the new operator

查看:74
本文介绍了JavaScript函数和新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向函数对象添加属性与向对象原型添加属性之间的区别是什么。请参阅下面的代码。

What is the difference between adding a property to a function object vs, adding a property to the objects prototype. See code below.

var foo = function() { this.name = alert("test") };

foo.newProp = function() { ... };
var value = new foo();

// vs

foo.prototype.newProp = function() { ... }
var value = new foo();

我的困惑是当为每个代码运行此代码时会发生什么值,以及'this'是怎样的受影响。

My confusion is what happens to value when this code is run for each, AND how 'this' is affected.

推荐答案

首先,我们知道函数只是对象,因为我们可以为它附加属性。这就是案例1中发生的事情。
我们只是将一个属性附加到函数Foo

Firstly, we know that functions are nothing but objects as we can attach properties to it. That is what is happening in the case1. We are just simply attaching a property to a function Foo

案例1

var Foo = function(){
    this.name = "myname";
}

Foo.newProp = function(){}; 

可以简单地访问附加到函数的属性,作为访问对象属性的方式。

The property attached to the function can be simply accessed as how we access properties of an object.

案例2

在这种情况下,相同的属性位于<$ c该功能的$ c> prototype 。当使用此函数Foo 创建任何对象时,默认情况下它将访问此函数。

In this case the same property is sitting on the prototype of that function. When any object is created using this function Foo, it will get access to this function by default.

调用时使用该对象的函数,上下文 this 将知道调用该函数的对象和这个指向调用它的对象。

When calling the function using that object, the context this will know the object calling that function and this points to the object calling it.

Foo.prototype.newProp = function(){ console.log("function on prototype");}

var value = new Foo();

console.log(value);

同样在案例2中,因为我们要向函数原型添加属性,所以它们不会坐在使用该函数但在该对象的proto上创建的对象上。查看下面显示的屏幕截图:

Also in case 2, since we are adding properties to the prototype of the function, they are not sitting on the object made using that function but on the proto of that object. Check this screenshot shown below:

< img src =https://i.stack.imgur.com/whP0a.pngalt =在此处输入图像说明>

这意味着有一个公共内存位置,访问该属性的每个对象都将指向它,因此它也具有内存效率。

That means there is a common memory location to which every object accessing that property will be pointing and hence it is memory efficient as well.

您可以随时继续修改该属性通过直接在对象上定义它来覆盖它:

You can always go ahead and modify that property by overriding it by defining it directly on the object as:

value.newProp = function(){ console.log("modified property") };

现在,如果你调用这个函数,它会直接在对象上找到它而不会下去原型链从公共内存位置访问它,即函数的原型Foo

Now, if you call this function, it will find it directly on the object and wont go down the prototype chain to access it from the common memory location i.e prototype of the function Foo

这篇关于JavaScript函数和新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆