初見此題,沒啥好說的,腦海中閃現以下兩種方式:javascript
//字面量
var obj={};
//new實例化
var obj=new Object();複製代碼
難度就這麼點?百度查了查,發現本身理解得有些片面了。以下正解:java
function createPerson(name) {
var obj = {};
obj.name = name;
obj.sayMyname = function() {
console.log(this.name);
};
return obj;
}
var p1 = createPerson('Mike');
p1.sayMyname(); //Mike
var p2 = createPerson('Lily');
p2.sayMyname(); //Lily
console.log(p1 instanceof createPerson); //false
console.log(p1 instanceof Object); //true
console.log(p2 instanceof createPerson); //false
console.log(p2 instanceof Object); //true複製代碼
能夠明顯的感受到,用此方法建立的對象沒法識別創造者(這裏的創造者全是Object)。app
當new去調用一個函數,這個時候函數中的this就是建立出來的對象,並且函數的返回值就是this(隱式返回)。ide
function createPerson(name) {
this.name = name;
this.sayMyname = function() {
console.log(this.name);
};
}
var p1 = new createPerson('Mike');
p1.sayMyname(); //Mike
var p2 = new createPerson('Lily');
p2.sayMyname(); //Lily
console.log(p1 instanceof createPerson); //true
console.log(p1 instanceof Object); //true
console.log(p2 instanceof createPerson); //true
console.log(p2 instanceof Object); //true複製代碼
function Person() {}
Person.prototype.name = 'Mike';
Person.prototype.sayMyname = function() {
console.log(this.name);
};
var p1 = new Person();
p1.sayMyname();複製代碼
function CreatePerson(name) { this.name = name;}CreatePerson.prototype.sayMyname = function() { console.log(this.name);};var p1 = new CreatePerson('Mike');p1.sayMyname();var p2 = new CreatePerson('Lily');p2.sayMyname();console.log(p1.sayMyname == p2.sayMyname); //true;緣由:都是在原型下面,在內存中只存在一份,地址相同複製代碼
屬性是否要放在原型下面,就要看該屬性是不是可變的,若是不是可變的,就能夠放在原型下面,用來公用屬性,可變的話放在構造函數下面。函數