js工厂模式的无法识别对象类型与构造函数在哪体现?

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);

请问从哪体现呢?
阅读 4.5k
3 个回答
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 ?   
和工厂模式关系在哪里?

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.

1)创建对象的过程中并没有体现出工厂模式。
2)可以了解下js通过构造函数创建对象的过程,应该就能解释 console.log(A1 instanceof A); //不是A的实例吗?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题