鍍金池/ 問答/HTML5  HTML/ js工廠模式的無法識別對象類型與構(gòu)造函數(shù)在哪體現(xiàn)?

js工廠模式的無法識別對象類型與構(gòu)造函數(shù)在哪體現(xiàn)?

function A(name,age) {
    var o = new Object()
    o.name = name
    o.age = age
    o.sayName = function () {
        alert(this.name)
    }
    return o
}
var A1 = new A('qwe',18)
console.log(A1 instanceof A);  //不是A的實例嗎?
console.log(A1 instanceof Object);

function B(name,age) {
    this.name = name
    this.age = age
}
var B1 = new B('asd', 12)
console.log(B1 instanceof B);
console.log(B1 instanceof Object);

請問從哪體現(xiàn)呢?
回答
編輯回答
冷溫柔

1)創(chuàng)建對象的過程中并沒有體現(xiàn)出工廠模式。
2)可以了解下js通過構(gòu)造函數(shù)創(chuàng)建對象的過程,應(yīng)該就能解釋 console.log(A1 instanceof A); //不是A的實例嗎?

2018年1月4日 02:46
編輯回答
青瓷

var A1 = new A('qwe', 18)這句:

  1. "new" will create an empty object first, and assign property through this.
  2. If there is no return or an primitive return inside the function, it will return the new created object to A. But if there is a non-primitive returning inner the function, like an object, array, or function , it will return the non-primitive to A.

function A(name,age) {
    var o = new Object()
    o.name = name
    o.age = age
    o.sayName = function () {
        alert(this.name)
    }
    return 1;
}
var A1 = new A('qwe',18); // A1 is a instance of A.

function A(name,age) {
    var o = new Object()
    o.name = name
    o.age = age
    o.sayName = function () {
        alert(this.name)
    }
    return {};
}
var A1 = new A('qwe',18); // A1 is a instance of object.
2017年9月17日 17:37
編輯回答
淺淺
function A(name,age) {
    var o = new Object()
    o.name = name
    o.age = age
    o.sayName = function () {
        alert(this.name)
    }
    return null;
}
var A1 = new A('qwe',18)
A1 instanceof A ?   
和工廠模式關(guān)系在哪里?
2017年10月22日 11:57