Javascript作用域/this

Javascript作用域/this,javascript,this,Javascript,This,为什么我会这样做: function Dog(){ this.firstName = 'scrappy'; } Dog.firstName未定义 不过,我可以做到: Dog.firstName = 'scrappy'; 现在Dog.firstName返回'scrapy' 为什么当我狗。名字未定义 因为 Dog从未被调用,因此行this.firstName='scrasty'从未执行,并且 。。。即使您调用函数,此可能也不会引用函数狗。你可以这样称呼它:this指的是Dog,但这很不寻

为什么我会这样做:

function Dog(){
   this.firstName = 'scrappy';
}
Dog.firstName未定义

不过,我可以做到:

Dog.firstName = 'scrappy';
现在Dog.firstName返回'scrapy'

为什么当我<代码>狗。名字未定义

因为

  • Dog
    从未被调用,因此行
    this.firstName='scrasty'从未执行,并且

  • 。。。即使您调用函数,
    可能也不会引用函数
    。你可以这样称呼它:
    this
    指的是
    Dog
    ,但这很不寻常

然而,我可以做到。。。现在Dog.firstName返回'scrapy'

函数只是对象,因此您可以为其分配任何属性。

函数
Dog()
只是构造函数,因此您在构造函数上调用
firstname
,而不是它的实例。这不仅仅是因为它是在返回的对象上定义的,它们是完全不同的东西。但是,由于可以使用字段扩充函数,因此仍然可以为dog.firstName赋值

首先,让我演示构造函数和实例之间的区别:

function Dog() {
    this.firstName = 'scrappy';
}

Dog.firstname; // undefined on the constructor

Dog.prototype; // defined on constructor, returns an empty object

var myDog = new Dog();

myDog.firstname; // defined on instance, returns 'scrappy'

myDog.prototype; // undefined on instance
如您所见,构造函数(返回对象的函数)与它返回的对象完全不同,因此具有完全不同的字段。当Dog.firstname返回“scrasty”时,您看到的是在构造函数中添加新字段的结果。这是可行的,但请记住,将字段添加到构造函数不会将同一字段添加到构造的。考虑:

Dog.someNewProperty = 'whatever';

var myDog = new Dog();

Dog.someNewProperty; // 'whatever'
myDog.someNewProperty; // undefined

你为什么要删除你的问题并再次发布?