如何向函数添加属性与添加到函数构造函数不同

时间:2015-05-09 15:56:29

标签: javascript

如何向“new add()。city”和“add()。city”添加属性     是不同的。

function add()
{
  this.name = 'suresh';
   this.lastname = 'kumar';
 }

  var b  =  new add();
  b.city = 'coimbatore';   

 add.city = 'coimbatore'     // how this is different from a above statement

2 个答案:

答案 0 :(得分:1)

  • 在第一个示例中,您正在创建一个add作为的新对象 构造函数,并为其提供自己的属性

  • 在第二个示例中,您将为add函数对象提供一个 自有财产

所以你在两种情况下做的几乎都是一样的。如果你更改add的原型,那么就会有所不同,然后你会在用new add()创建的所有对象中使所述属性'可继承'。

function add() {
    this.name = 'suresh';
    this.lastname = 'kumar';
}

var b = new add();

// Adds property to the new b object, whose constructor is add.
// Only b will have this property.
b.city = 'coimbatore';

// Adds property ONLY to the function object.
// Objects created with add as a constructor won't 'inherit' it
// Only `add` will have this property (although in this case,
// b has a property named the same way, with the same value,
// but they are own properties of each object).
add.city = 'coimbatore';

// Adds property to add's prototype. Objects created with `add`
// as a constructor will inherit it. ( for instance `var z =  new add()` )

add.prototype.hello = 'there';

console.log(b.hello); // 'there'

var c = new add();
console.log(c.hello); // 'there'

// Adds own property to the `c` object.
// Only c will have this property:

c.myVeryOwnProperty = 'yeaah!';
console.log( c.myVeryOwnProperty ); // 'yeaah!'
console.log( b.myVeryOwnProperty ); // undefined
console.log( add.myVeryOwnProperty ); // undefined

// Now, check this out:

// True, because you set the properties directly on the object
console.log( add.hasOwnProperty('city') ); // true
console.log( b.hasOwnProperty('city') ); // true
console.log( c.hasOwnProperty('myVeryOwnProperty') ); // true

// False, because these objects got the `hello` property
// through add's prototype
console.log( b.hasOwnProperty('hello') ); // false
console.log( c.hasOwnProperty('hello') ); // false

答案 1 :(得分:1)

证明差异的最简单方法是从示例中删除其中一行并查​​看我们的内容

function add() {
    this.name = 'suresh';
    this.lastname = 'kumar';
}

var b = new add();
// b.city = 'coimbatore'; // this line removed

add.city = 'coimbatore';

现在,b.city是什么?

b.city; // undefined

未来的实例也不会有城市房产,因此不仅仅是导致b没有设置的设置顺序。

var c = new add();
c.city; // undefined

这意味着在构造函数上设置属性对它构造的对象没有影响(有一些特殊的例外,例如 prototype 属性)

这种情况正在发生,因为add构造函数是它自己的 Object ,而new add创建的对象是 {{em> {{ 1}},所以继承自add,而不是add.prototype本身。

如果您希望每个实例都继承某些内容,并且如果它们不是拥有属性就可以,那么您可以将它们添加到构造函数的原型中。如果您正在添加对象,请务必小心,因为对它们的任何更改都将针对所有实例进行修改。

考虑

add

我用 Objects

警告过的危险
add.prototype.city = 'coimbatore';
b.city; // "coimbatore"
// and don't have to worry if you change it on an instance
b.city = 'fizz';
c.city; // "coimbatore"