H5W3
当前位置:H5W3 > 其他技术问题 > 正文

【Web前端问题】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);

请问从哪体现呢?

回答:

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的实例吗?

本文地址:H5W3 » 【Web前端问题】js工厂模式的无法识别对象类型与构造函数在哪体现?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址